Capítulo 357 de 456
getServerSideProps (Pages Router) fetches data at request time and renders the page server-side on every visit. Use it for personalized/request-dependent data (auth headers, geolocation); otherwise prefer getStaticProps with ISR.
getServerSideProps: exported async function from a page file; runs only on the server, returns { props } as JSON.next/link, which trigger a server request that re-runs it.props returned are embedded in the initial HTML and visible client-side — never put sensitive data there.pages/500.js (custom 500 page); in dev, the error overlay is shown instead.import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = { name: string; stargazers_count: number }
export const getServerSideProps = (async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo: Repo = await res.json()
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return <p>{repo.stargazers_count}</p>
}
GetServerSideProps<T> e InferGetServerSidePropsType para inferir o shape das props na página.export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return { props: {} }
}
Cache-Control com stale-while-revalidate, embora getStaticProps + ISR seja geralmente preferível.props: eles ficam expostos no HTML inicial para hidratação client-side.getServerSideProps quando ISR resolveria: perde cache/prerender sem necessidade real de dado por-requisição.stale-while-revalidate é a via de otimização quando SSR é obrigatório.pages/500.js.