Capítulo 376 de 456

getInitialProps

Core Idea

getInitialProps is a legacy async data-fetching function attached to a page's default export; superseded by getStaticProps/getServerSideProps.

Key Concepts

  • Page.getInitialProps: runs server-side on initial load, and again client-side on next/link/next/router navigation.
  • Context object: receives pathname, query, asPath, req (server-only), res (server-only), err.
  • _app.js interaction: if used in a custom _app.js alongside a page using getServerSideProps, getInitialProps runs server-only.

Code Examples

import { NextPageContext } from 'next'

Page.getInitialProps = async (ctx: NextPageContext) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default function Page({ stars }: { stars: number }) {
  return stars
}
  • O que demonstra: attaching getInitialProps to a page component and consuming the returned props.

Reference Tables

Context propertyDescription
pathnamecurrent route path
queryparsed query string object
asPathactual browser path incl. query
reqHTTP request (server only)
resHTTP response (server only)
errerror encountered during rendering

Anti-patterns

  • Using in nested components: only works in top-level pages/ files, not nested components.
  • Returning non-serializable data (Date, Map, Set): breaks serialization during server rendering.
  • Passing sensitive data in returned props: it's exposed in the initial HTML for hydration; never include secrets.

Key Takeaways

  1. Prefer getStaticProps/getServerSideProps for new code; getInitialProps is legacy.
  2. It fetches on both server (initial load) and client (subsequent navigation) — unlike getStaticProps/getServerSideProps.
  3. Return values must be plain serializable objects.

Connects To

  • getServerSideProps: modern replacement for per-request data fetching.
  • getStaticProps: modern replacement for build-time data fetching.