CodePark/ questions / Data fetching & caching
START PRACTICINGPRACTICE
Frontend question · Next.js › Data fetching & caching

How do you fetch data in the App Router?

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const [user, posts] = await Promise.all([
    getUser(id),
    getPosts(id),
  ]);
  return <Profile user={user} posts={posts} />;
}

In a Server Component, make the component async and await the data directly.

You can:

  • fetch an API
  • query a database with an ORM
  • call any server function

You need no useEffect and no extra API layer. Secrets never reach the browser.

Avoid accidental waterfalls. A waterfall is when requests run one after another even though they don't depend on each other, so the waits add up. If two requests are independent, start them together and await them with Promise.all. Wrap slow parts in Suspense, so the rest of the page can stream to the browser first.

Some data must load in the browser, for example after a user clicks something, or for polling. For that, use one of these:

  • a Client Component with a library like SWR or React Query
  • a Promise passed from a Server Component, unwrapped with React's use()
  • Async Server Components await their data directly.
  • A Server Component can query the database without an API route.
  • Use Promise.all to run independent requests at the same time.
  • Wrap slow data in Suspense so the rest of the page streams first.
  • For browser-side fetching, use SWR, React Query or use() with a passed Promise.