getInitialProps
Good to know:
getInitialProps
is a legacy API. We recommend usinggetStaticProps
orgetServerSideProps
↗ 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
getInitialProps
is serialized when server rendering. Ensure the returned object fromgetInitialProps
is a plainObject
, and not usingDate
,Map
orSet
.- For the initial page load,
getInitialProps
will run on the server only.getInitialProps
will then also run on the client when navigating to a different route with thenext/link
component or by usingnext/router
.- If
getInitialProps
is used in a custom_app.js
, and the page being navigated to is usinggetServerSideProps
, thengetInitialProps
will 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
getInitialProps
can 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
getInitialProps
asprops
will 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