Fetching Data on the Server with fetch

Next.js extends the native fetch Web API

 to allow you to configure the caching and revalidating behavior for each fetch request on the server. React extends fetch to automatically memoize fetch requests while rendering a React component tree.

You can use fetch with async/await in Server Components, in Route Handlers, and in Server Actions.

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

  • Next.js provides helpful functions you may need when fetching data in Server Components such as cookies and headers. These will cause the route to be dynamically rendered as they rely on request time information.
  • In Route handlers, fetch requests are not memoized as Route Handlers are not part of the React component tree.
  • In Server Actionsfetch requests are not cached (defaults cache: no-store).
  • To use async/await in a Server Component with TypeScript, you’ll need to use TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher.

Leave a comment

Your email address will not be published. Required fields are marked *