Capítulo 357 de 456

getServerSideProps

Core Idea

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.

Key Concepts

  • getServerSideProps: exported async function from a page file; runs only on the server, returns { props } as JSON.
  • Request-time execution: runs on every request/navigation, including client-side navigations via next/link, which trigger a server request that re-runs it.
  • Props hydration: props returned are embedded in the initial HTML and visible client-side — never put sensitive data there.
  • No API Route needed: since it runs server-side, call a DB/CMS/third-party API directly instead of hitting your own API Route.
  • Error page: an uncaught error inside it renders pages/500.js (custom 500 page); in dev, the error overlay is shown instead.

Code Examples

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>
}
  • O que demonstra: tipagem com 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: {} }
}
  • O que demonstra: cache de resposta SSR via header Cache-Control com stale-while-revalidate, embora getStaticProps + ISR seja geralmente preferível.

Anti-patterns

  • Passar dados sensíveis em props: eles ficam expostos no HTML inicial para hidratação client-side.
  • Usar getServerSideProps quando ISR resolveria: perde cache/prerender sem necessidade real de dado por-requisição.

Key Takeaways

  1. Só pode ser exportado de uma page, nunca de componente comum.
  2. Roda 100% no servidor: pode acessar banco/CMS direto, sem round-trip por API Route própria.
  3. Cache-Control com stale-while-revalidate é a via de otimização quando SSR é obrigatório.
  4. Erro não tratado cai no pages/500.js.

Connects To

  • getStaticProps + ISR: alternativa preferida quando o dado não precisa ser por-requisição.
  • Client-side Fetching (ch358): alternativa para dados que não precisam de SEO/prerender.