7

I want to be able to have a 'master' HEAD element in _document.js and for certain pages have an additional HEAD element that adds to what is in the 'master'. From https://nextjs.org/docs/api-reference/next/head it would seem that this is possible.

However, when searching for the answer in Stack Overflow, I found this post, which seems to indicate that this can lead to unexpected results.

If I can't have multiple HEAD elements, do I need to pass data from the individual page through getInitialProps?

Cerulean
  • 5,543
  • 9
  • 59
  • 111
  • 1
    The intention of the library is that it is additive as you suspect. The post to which you link seems rather like superstitious programming; the author offers no concrete evidence, only conjecture, and they clearly don't display an understanding of the behavior they observe either. – Patrick Roberts Feb 25 '20 at 15:54

1 Answers1

10

You can simple import next/head into any page/component when you need to do something with it

Example:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

and also have a default Head within _document.js

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

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <link rel="shortcut icon" href="/favicon.ico" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

I am not experiencing any issue so far.

Something to remember though:

The contents of head get cleared upon unmounting the component, so make sure each page completely defines what it needs in head, without making assumptions about what other pages added.

ddon-90
  • 2,816
  • 1
  • 20
  • 29