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
cookiesandheaders. These will cause the route to be dynamically rendered as they rely on request time information. - In Route handlers,
fetchrequests are not memoized as Route Handlers are not part of the React component tree. - In Server Actions,
fetchrequests are not cached (defaultscache: no-store). - To use
async/awaitin a Server Component with TypeScript, you’ll need to use TypeScript5.1.3or higher and@types/react18.2.8or higher.