-1

I'm new to Next.js and trying to use the new app router (i.e. place my pages under app/.../page.tsx)

The following works in page router (pages/blah.tsx) but not in app/blah/page.tsx . app router doesn't call getServerSideProps at all and passes empty params to the page function.

Why? How do I use getServerSideProps in app router?

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getServerSideProps: GetServerSideProps<{
  repo: Repo
}> = async () => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  return { props: { repo } }
}
 
export default function Page({
  repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return <div>{repo.stargazers_count}</div>
}
  • 1
    Read e.g. https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#server-side-rendering-getserversideprops – jonrsharpe Jul 17 '23 at 15:08

1 Answers1

0

As @jonrsharpe commented, the new app router uses new, simpler mechanics of Server-side Components and you can't simply move code from pages to app.

Re-posting link.

The following works:

type Repo = {
  name: string
  stargazers_count: number
}
 
async function getServerSideProps()
{
  const res = await fetch('https://api.github.com/repos/vercel/next.js');
  const repo = await res.json();
  return repo;
}
 
export default async function Page() {
  try{
  const repo = await getServerSideProps();
  return <div>Stargazers : {repo.stargazers_count}</div>
  } catch( error ){
    return <div>Error fetching: {JSON.stringify( error) }</div>
  }
}