Carwyn Stephen
Carwyn Stephen

Reputation: 134

NextJS Head component renders stale props

My goal is to try and put this tag in my NextJS' app's head:

<link rel="canonical" href="http://stackoverflow.com" />

I have set up a custom _app.js, and in the getInitialProps I return my URL by using the url package. This works fine and I get the url on page load. This is the code for this:

static async getInitialProps({ Component, ctx }) {
    const initialProps = {};

    if (isServer) {
        const { req: { url: pageUrl, headers: { host } } } = ctx;

        initialProps.canonicalHref =
        createUrl({subdomain: host.split('.')[0], pathname: url.parse(pageUrl).pathname});
    }

    return  { ...initialProps }
}

And in my render function I use this to render the link tag:

        <Head>
          <link rel="canonical" href={canonicalHref || location.host + router.asPath} key="canonical" />
        </Head>

The idea is that getInitialProps returns the first value, then on the client side it returns null, making it fall back to location.host + router.asPath.

The only problem is that router.asPath seems to be one step behind the actual value whenever it updates. For example say if I'm on 'http://bla.com/two' and my previous page was 'http://bla.com/one' then the link will render as <link rel="canonical" href="http://bla.com/one" />.

I hope I've explained myself well enough here and I hope someone has any ideas to help :)

Upvotes: 0

Views: 1280

Answers (1)

evgeni fotia
evgeni fotia

Reputation: 4810

if it's in the render then just use location.href instead of location.host + router.asPath also if you want to know more about why router.asPath shows previous URL

Upvotes: 1

Related Questions