React
Next.js
2 minute read | February 22, 2024

Loading data on the server with the Next.js App Router

Previously with the Next.js Pages Router we would have loaded data using the getServerSideProps() function. This is no longer available with the App Router so how do we accomplish the same thing.

Example

With the old Pages Router we would have had something like the following. At request time this simply fetches some posts and passes them as props to our page.

Javascript
export const getServerSideProps = async () => { const response = await fetch('some url'); const posts = await response.json(); return { props: { posts } } }; const Page = ({ posts }) => { return ( ...some ui ); }; export default Page;

We can't use getServerSideProps() with the App Router but it's actually now much simplier to implement. We'll simply make our page async and fetch the data directly.

Your page must be a React Server Component in order to fetch data on the server

Javascript
const Page = async () => { const response = await fetch('some url'); const posts = await response.json(); return ( ...some ui ); }; export default Page;