# getInitialProps

推荐: getStaticPropsgetServerSideProps

如果你使用的是 Next.js 9.3 或更高版本,我们建议你使用 getStaticPropsgetServerSideProps来替代 getInitialProps

这些新的获取数据的方法使你可以在静态生成(static generation)和服务器端渲染(server-side rendering)之间进行精细控制。更多信息请参考 页面(Pages)数据获取 文档。

getInitialPropsenables server-side rendering](/docs/basic-features/pages#server-side-rendering) in a page and allows you to do **initial data population**, it means sending thepagewith the data already populated from the server. This is especially useful for [SEO .

getInitialPropswill disable Automatic Static Optimization .

getInitialPropsis an async function that can be added to any page as a static method . Take a look at the following example:

function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

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

export default Page

Or using a class component:

import React from 'react'

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

  render() {
    return <div>Next stars: {this.props.stars}</div>
  }
}

export default Page

getInitialPropsis used to asynchronously fetch some data, which then populates props.

Data returned from getInitialPropsis serialized when server rendering, similar to what JSON.stringify does. Make sure the returned object from getInitialPropsis a plain Objectand not using Date, Mapor Set.

For the initial page load, getInitialPropswill run on the server only. getInitialPropswill then run on the client when navigating to a different route via the next/link component or by using next/router . However, if getInitialPropsis used in a custom _app.js, and the page being navigated to implements getServerSideProps, then getInitialPropswill run on the server.

# Context Object

getInitialPropsreceives a single argument called context, it's an object with the following properties:

  • pathname- Current route. That is the path of the page in /pages
  • query- Query string section of URL parsed as an object
  • asPath- Stringof 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 notbe used in children components, only in the default export of every page
  • If you are using server-side only modules inside getInitialProps, make sure to import them properly , otherwise it'll slow down your app

# TypeScript

If you're using TypeScript, you can use the NextPagetype for function components:

import { NextPage } from 'next'

interface Props {
  userAgent?: string;
}

const Page: NextPage<Props> = ({ userAgent }) => (
  <main>Your user agent: {userAgent}</main>
)

Page.getInitialProps = async ({ req }) => {
  const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
  return { userAgent }
}

export default Page

And for React.Component, you can use NextPageContext:

import React from 'react'
import { NextPageContext } from 'next'

interface Props {
  userAgent?: string;
}

export default class Page extends React.Component<Props> {
  static async getInitialProps({ req }: NextPageContext) {
    const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
    return { userAgent }
  }

  render() {
    const { userAgent } = this.props
    return <main>Your user agent: {userAgent}</main>
  }
}

For more information on what to do next, we recommend the following sections:

Data FetchingLearn more about data fetching in Next.js. PagesLearn more about what pages are in Next.js. Automatic Static OptimizationLearn about how Next.js automatically optimizes your pages.

Last Updated: 5/13/2023, 8:55:38 PM