Skip to main content

Server

The Next.js App Router introduces a new, simplified data fetching system built on React and the Web platform. This page will go through the fundamental concepts and patterns to help you manage your data's lifecycle.

Fetching data in the server - Next.js 13.2

Whenever possible, we recommend fetching data inside Server Components. Server Components always fetch data on the server. This allows you to:

  • Have direct access to backend data resources (e.g. databases).
  • Keep your application more secure by preventing sensitive information, such as access tokens and API keys, from being exposed to the client.
  • Fetch data and render in the same environment. This reduces both the back-and-forth communication between client and server, as well as the work on the main thread on the client.
  • Perform multiple data fetches with single round-trip instead of multiple individual requests on the client. Reduce client-server waterfalls.
  • Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance.
tip

Good to know: Previous Next.js data fetching methods such as getServerSideProps, getStaticProps, and getInitialProps are not supported in the new app directory.

async/await in Server Components

With the proposed React RFC, you can use async and await to fetch data 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>;
}
danger

Async Server Component TypeScript Error

An async Server Components will cause a Promise<Element> is not a valid JSX element type error where it is used. This is a known issue with TypeScript and is being worked on upstream. As a temporary workaround, you can add {/_ @ts-expect-error Async Server Component _/} above the component to disable type checking for it.

Resources