Can you have multiple, additive 'HEAD' elements in NextJS?

Viewed 1593

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?

1 Answers

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.

Related