I tried to copy/paste the official examples from NextJS for getServerSideProps and it throws errors:
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 repo.stargazers_count
}
Error:
./app/page.tsx
ReactServerComponentsError:
"getServerSideProps" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching
Unfortunately, it refers to data-fetching documentation, which contains the example that led me to this error.
Create the app:
npx create-next-app@latest
(TypeScript: yes, AppRouter: yes, src-directory: no)
Change the pages.tsx into the variant above from the Docs.
package.json:
"scripts": {
"dev": "next dev -p 8002",
"build": "next build",
"start": "next start -p 8002",
"lint": "next lint"
},
"dependencies": {
"@types/node": "20.4.2",
"@types/react": "18.2.15",
"@types/react-dom": "18.2.7",
"autoprefixer": "10.4.14",
"eslint": "8.45.0",
"eslint-config-next": "13.4.10",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^5.0.0",
"next": "13.4.10",
"postcss": "8.4.26",
"prettier": "^3.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"tailwindcss": "3.3.3",
"typescript": "5.1.6"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.1.0"
}
How to deal with that and how to use getServerSideProps with AppRouter?
In order to use getServerSideProps, your component needs to be in the /pages directory. I changed the structure of your example like so and got it working:
my-app/
├─ node_modules/
├─ app/
│ ├─ globals.css
│ ├─ layout.tsx
├─ .gitignore
├─ package.json
├─ README.md
├─ pages/
│ ├─ index.tsx
Moving your code there will solve your issue. This is because components in the /pages directory are treated specially. You can read more here, but in short, next automatically handles routing based on the pages directory and executes server-side logic before returning your page. Doing so in a non-page component would not work since those are provided after the page load (e.g. not server-side rendered)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With