Capítulo 377 de 456

getServerSideProps

Core Idea

Exporting getServerSideProps from a page makes Next.js prerender it on every request using the returned data, ideal for frequently-changing content.

Key Concepts

  • Context parameter: object with params, req, res, query, preview/previewData (deprecated for draftMode), draftMode, resolvedUrl, locale, locales, defaultLocale.
  • props: serializable key-value object passed to the page component.
  • notFound: true returns a 404, even overriding a previously successful build.
  • redirect: { destination, permanent } (or statusCode instead of permanent, not both).
  • Server-only imports: modules imported at top-level scope in the file are not bundled for the client.

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 <main><p>{repo.stargazers_count}</p></main>
}
  • O que demonstra: typed getServerSideProps with satisfies and InferGetServerSidePropsType.

Reference Tables

Context keyDescription
paramsdynamic route params
req / resHTTP request/response objects
queryfull query string object
resolvedUrlnormalized URL, strips _next/data prefix
locale / locales / defaultLocalei18n info

Anti-patterns

  • Setting both statusCode and permanent on redirect: not supported, choose one.
  • Returning non-serializable props: must be JSON-serializable.

Key Takeaways

  1. Runs on every request server-side, no static caching like getStaticProps.
  2. App Router's simplified data fetching (stable since v13.4.0) is the long-term replacement.
  3. preview/previewData are deprecated in favor of draftMode.

Connects To

  • getStaticProps: build-time counterpart, with revalidate for ISR.
  • getInitialProps: older, dual-execution (server+client) legacy API.