Capítulo 379 de 456

getStaticProps

Core Idea

Exporting getStaticProps prerenders a page at build time using the returned props, forming the basis of Static Generation and Incremental Static Regeneration (ISR).

Key Concepts

  • Context parameter: params, preview/previewData (deprecated for draftMode), draftMode, locale, locales, defaultLocale, revalidateReason ("build" | "stale" | "on-demand").
  • props: serializable object passed to the page.
  • revalidate: seconds after which regeneration may occur (ISR); default false (no revalidation).
  • notFound: returns 404, follows the same revalidate behavior.
  • redirect: { destination, permanent } or statusCode instead of permanent; supports basePath: false.
  • x-nextjs-cache header: MISS/STALE/HIT reveals ISR cache status.
  • process.cwd(): correct way to read files from disk inside getStaticProps (not __dirname, which resolves incorrectly after Next.js's build-time relocation).

Code Examples

export const getStaticProps = (async (context) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  return { props: { repo } }
}) satisfies GetStaticProps<{ repo: Repo }>
  • O que demonstra: typed build-time fetch returning props.
export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()
  return {
    props: { posts },
    revalidate: 10, // regenerate at most once every 10s
  }
}
  • O que demonstra: ISR via revalidate.
import { promises as fs } from 'fs'
import path from 'path'

export async function getStaticProps() {
  const postsDirectory = path.join(process.cwd(), 'posts')
  const filenames = await fs.readdir(postsDirectory)
  // ...
}
  • O que demonstra: safe filesystem access using process.cwd().

Reference Tables

Return valuePurpose
propsdata passed to the page component
revalidateISR interval in seconds
notFoundrender 404
redirect{ destination, permanent } or statusCode

Anti-patterns

  • Using __dirname for file paths: breaks because Next.js compiles into a different directory structure; use process.cwd().
  • Setting both statusCode and permanent: not allowed on redirect.
  • Hardcoding build-time-known redirects here: put those in next.config.js redirects instead.

Key Takeaways

  1. getStaticProps code and its imports never ship to the client bundle, safe for direct DB/database queries.
  2. revalidate is the mechanism for ISR; omit it for pure static generation.
  3. revalidateReason tells you whether a call is the initial build, a stale-triggered regen, or an on-demand revalidation.
  4. App Router's simplified data fetching (stable v13.4.0) supersedes this API long-term.

Connects To

  • getStaticPaths: required companion for dynamic routes.
  • Incremental Static Regeneration guide: deeper coverage of revalidate and on-demand revalidation.