Capítulo 376 de 456
getInitialProps is a legacy async data-fetching function attached to a page's default export; superseded by getStaticProps/getServerSideProps.
Page.getInitialProps: runs server-side on initial load, and again client-side on next/link/next/router navigation.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.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
}
getInitialProps to a page component and consuming the returned props.| Context property | Description |
|---|---|
pathname | current route path |
query | parsed query string object |
asPath | actual browser path incl. query |
req | HTTP request (server only) |
res | HTTP response (server only) |
err | error encountered during rendering |
pages/ files, not nested components.Date, Map, Set): breaks serialization during server rendering.getStaticProps/getServerSideProps for new code; getInitialProps is legacy.getStaticProps/getServerSideProps.