Ronald
Ronald

Reputation: 2932

Next.js: Access request (ctx.req) in "getInitialProps" method in custom Document "_document"

I have created a blank Next.js app:

npx create-next-app

I have added a custom Document https://nextjs.org/docs/advanced-features/custom-document

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);

    console.log("ctx: " + JSON.stringify(ctx, null, 2));

    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          Test
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

I would like to access "ctx.req" in getInitialProps but as can be seen by the log message "ctx" does not contain the "req" object. Here is the log message:

ctx: {
  "pathname": "/",
  "query": {},
  "asPath": "/"
}

From https://nextjs.org/docs/advanced-features/automatic-static-optimization I understand that for prerendered pages ctx.req will be undefined:

"If you have a custom Document with getInitialProps be sure you check if ctx.req is defined before assuming the page is server-side rendered. ctx.req will be undefined for pages that are prerendered."

but on the other hand the same page also says:

"Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements. This determination is made by the absence of getServerSideProps and getInitialProps in the page."

From this I understand that if the method getInitialProps exists the page is regarded as non-prerenderable and instead server-side rendered.

What am I missing? How can I access the request in "getInitialProps" method in "_document"?

Upvotes: 3

Views: 7019

Answers (1)

Ronald
Ronald

Reputation: 2932

As soon as I add getServerSideProps to pages/index.js

export async function getServerSideProps() {
  const data = "myData";
  return { props: { data } };
}

Next.js really does render the page server-side and then ctx.req is available in "getInitialProps" method in "_document".

Upvotes: 3

Related Questions