#getServerSideProps in app router
1 messages · Page 1 of 1 (latest)
Hi @civic chasm. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
getServerSideProps is not supported in the new App Router. It is only available in the Pages Router. You can still use it in the Pages Router for fetching data on the server and returning generated HTML to the client. However, in the App Router, you can use Server Components for server-side rendering and data fetching. This allows you to send less JavaScript to the client while maintaining the rendered HTML from the server.
Here's an example of using getServerSideProps in the Pages Router:
// `pages` directory
export async function getServerSideProps() {
const res = await fetch(`https://...`);
const projects = await res.json();
return { props: { projects } };
}
export default function Dashboard({ projects }) {
return (
<ul>
{projects.map((project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
);
}
For more information on data fetching in the App Router, refer to the Next.js documentation on data fetching (https://nextjs.org/docs/app/building-your-application/data-fetching).
Source: App Router Migration (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@civic chasm kapa.ai is still learning and improving, please let us how it did by reacting below
Can you make the example using server components?
@waxen cave Can you make the example using server components?
Let me check the knowledge base for you. One moment! :books:
Sure, here's an example of fetching data on the server using Server Components in the App Router:
// app/dashboard/page.tsx
export default async function Page() {
const res = await fetch('https://api.example.com/...');
const projects = await res.json();
return (
<ul>
{projects.map((project) => (
<li key={project.id}>{project.name}</li>
))}
</ul>
);
}
In this example, the data fetching is colocated inside the React component using Server Components. This allows you to send less JavaScript to the client while maintaining the rendered HTML from the server.