#getServerSideProps in app router

1 messages · Page 1 of 1 (latest)

civic chasm
#

what is the version of using getServerSideProps in app router? I just want to fetch data on the server and return generated html to client

waxen caveBOT
#

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:

Learn how to upgrade your existing Next.js application from the Pages Router to the App Router.

#

@civic chasm kapa.ai is still learning and improving, please let us how it did by reacting below

civic chasm
#

Can you make the example using server components?

#

@waxen cave Can you make the example using server components?

waxen caveBOT
#

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.

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:

Learn how to upgrade your existing Next.js application from the Pages Router to the App Router.