なんでもノート

なんでも書くノートみたいなブログ

Next.jsのgetInitialPropsの実行順序

Next.jsのPage ComponentとCustom App ComponentとCustom Document ComponentのgetInitialPropsの実行順序を整理する。

// pages/index.tsx
...

Home.getInitialProps = async (ctx: NextPageContext) => {
  console.log("Home.getInitialProps");
  return { hoge: "fuga" };
};
// pages/_app.tsx
// @see https://nextjs.org/docs/basic-features/typescript#custom-app
import App from "next/app";
import type { AppProps, AppContext } from "next/app";

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

MyApp.getInitialProps = async (appContext: AppContext) => {
  console.log("MyApp.getInitialProps");
  const appProps = await App.getInitialProps(appContext);

  return { ...appProps };
};

export default MyApp;
// pages/_document.tsx
// @see https://nextjs.org/docs/advanced-features/custom-document#typescript
import Document, { DocumentContext } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    console.log("MyDocument.getInitialProps");
    const initialProps = await Document.getInitialProps(ctx);

    return initialProps;
  }
}

export default MyDocument;

ほぼドキュメントまま。

出力結果

MyApp.getInitialProps
Home.getInitialProps
MyDocument.getInitialProps

MyAppのgetInitialPropsでAppのgetInitialPropsを呼んでいるので、Page ComponentのgetInitialPropsが実行されていることは予想がつく。Custom DocumentのgetInitialPropsは最後に呼び出されるのは覚えておきたい。