How to Fetch Data in Nextjs 13 || Quick Guide for Beginners

This article shows upgrade guide of Nextjs 13

Blog post By Xyz - Published at 1/31/2023, 3:54:11 AM

How to Fetch Data in Nextjs 13 || Quick Guide for Beginners

Fetching data in Next.js is a common task for web developers, but it can be a little tricky to get started. This quick guide is designed to help beginners learn how to fetch data in Next.js 13 and take their skills to the next level.

What is Next.js

Next.js is a popular React-based framework for building server-side rendered (SSR) web applications. It's known for its ability to provide fast load times and SEO-friendly pages, making it a popular choice for developers looking to build scalable and performance-optimized web apps.

Why Fetch Data in Next.js

One of the key benefits of using Next.js is its ability to easily fetch data from external APIs and integrate it into your web pages. This allows you to create dynamic and engaging web pages that can be easily updated with new data.

Getting Started with Fetching Data in Next.js

To get started with fetching data in Next.js, you'll need to have a basic understanding of JavaScript and React. If you're new to these technologies, we recommend taking a few online courses or reading some beginner-friendly tutorials before diving into this guide.

  • With parallel data fetching, requests in a route are eagerly initiated and will load data at the same time. This reduces client-server waterfalls and the total time it takes to load data.
  • With sequential data fetching, requests in a route are dependent on each other and create waterfalls. There may be cases where you want this pattern because one fetch depends on the result of the other, or you want a condition to be satisfied before the next fetch to save resources. However, this behavior can also be unintentional and lead to longer loading times.

async/await in Server Components

async function getData() {
  const res = await fetch('https://api.example.com/...');
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  // Recommendation: handle errors
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export default async function Page() {
  const data = await getData();

  return <main></main>;
}
async function getData() {
  const res = await fetch('https://api.example.com/...');
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  // Recommendation: handle errors
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export default async function Page() {
  const data = await getData();

  return <main></main>;
}

Parallel Data Fetching

import Albums from './albums';

async function getArtist(username) {
  const res = await fetch(`https://api.example.com/artist/${username}`);
  return res.json();
}

async function getArtistAlbums(username) {
  const res = await fetch(`https://api.example.com/artist/${username}/albums`);
  return res.json();
}


export default async function Page({ params: { username } }) {
  // Initiate both requests in parallel
  const artistData = getArtist(username);
  const albumsData = getArtistAlbums(username);

  // Wait for the promises to resolve
  const [artist, albums] = await Promise.all([artistData, albumsData]);

  return (
    <>
      <h1>{artist.name}</h1>
      <Albums list={albums}></Albums>
    </>
  );
}

Data fetching without fetch()

import prisma from './lib/prisma';
//For Getserverside props / Getstaticside props 
export const dynamic = 'auto'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
//For ISR (Incremental static regeneration)
export const revalidate = 3600; // revalidate every hour
// for runtime
export const runtime = 'nodejs'
// 'experimental-edge' | 'nodejs'
async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

export default async function Page() {
  const posts = await getPosts();
  // ...
}

Community

Next.js is the result of the combined work of over 2,400 individual developers, industry partners like Google and Meta, and our core team at Vercel. With over 3.6 million npm downloads per week and 97,900+ GitHub stars, Next.js is one of the most popular ways of building the Web.

Join the community on GitHub Discussions, Reddit, and Discord.

This release was brought to you by: