getInitialProps
Good to know:
getInitialPropsis a legacy API. We recommend usinggetStaticPropsorgetServerSideProps↗ instead.
getInitialProps is an async function that can be added to the default exported React component for the page. It will run on both the server-side and again on the client-side during page transitions. The result of the function will be forwarded to the React component as props.
pages/index.tsx
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
}Good to know:
- Data returned from
getInitialPropsis serialized when server rendering. Ensure the returned object fromgetInitialPropsis a plainObject, and not usingDate,MaporSet.- For the initial page load,
getInitialPropswill run on the server only.getInitialPropswill then also run on the client when navigating to a different route with thenext/linkcomponent or by usingnext/router.- If
getInitialPropsis used in a custom_app.js, and the page being navigated to is usinggetServerSideProps, thengetInitialPropswill also run on the server.
Context Object
getInitialProps receives a single argument called context, which is an object with the following properties:
| Name | Description |
|---|---|
pathname |
Current route, the path of the page in /pages |
query |
Query string of the URL, parsed as an object |
asPath |
String of the actual path (including the query) shown in the browser |
req |
HTTP request object ↗ (server only) |
res |
HTTP response object ↗ (server only) |
err |
Error object if any error is encountered during the rendering |
Caveats
getInitialPropscan only be used inpages/top level files, and not in nested components. To have nested data fetching at the component level, consider exploring the App Router ↗.- Regardless of whether your route is static or dynamic, any data returned from
getInitialPropsaspropswill be able to be examined on the client-side in the initial HTML. This is to allow the page to be hydrated ↗ correctly. Make sure that you don’t pass any sensitive information that shouldn’t be available on the client inprops.
Last updated on