MrCakes
MrCakes

Reputation: 165

How to get pathname in NextJS /_document.js file

I'm trying to get the current pathname in /page/_document.js file. I'm using a class, and my objective is to make a conditional with that value.

Here's my code (is basically the example in NextJS' page)

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

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

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

export default MyDocument

Upvotes: 6

Views: 5428

Answers (1)

iamhuynq
iamhuynq

Reputation: 5529

You can get it by ctx.req.url or ctx.asPath but getInitialProps only executed at first time you access to app

Note: 's getInitialProps function is not called during client-side transitions, nor when a page is automatically statically optimized.

Note: Make sure to check if ctx.req / ctx.res are defined in getInitialProps. These variables will be undefined when a page is being statically exported for next export or automatic static optimization.

Document

Upvotes: 3

Related Questions