next.js: Duplicate meta tags when using Head both in custom document and page

Bug report

Edit +++ ON HOLD I just had a lightbulb moment. I will post my discovery/misunderstanding in the next few hours. This ticket can probably be closed then, but I have to test my new theory first…

Describe the bug

Multiple (duplicate) meta tags such as charSet and viewport are rendered in <head> section of the HTML output when the <Head> component is used in both a custom _document and a page file.

Even relying on the default injection of <meta charSet="utf-8"/> (i.e. not specifying that tag at all) results in having two of the same tags in the output HTML, one from Document and one from the page.

I also end up with two viewport meta tags, one from Document and one from the page.

To Reproduce

I have created (failing) tests here: https://github.com/Manc/next.js/tree/test-head-document

  1. Clone repository git@github.com:Manc/next.js.git
  2. Check out branch test-head-document
  3. yarn install
  4. yarn testonly --testPathPattern "app-document" -t "It dedupes head tags with the same key"

Expected behavior

I expect the meta tags with the same key to override the meta tags from the custom Document (_document).

I expect only to have one charset and one viewport tag in the whole rendered HTML.

System information

  • OS: macOS
  • Version of Next.js: latest or canary branch

Other

I’m pretty new to Next.js and don’t really know how it all works yet. I hope the test I provided helps somebody more experienced to fix this or maybe give me a hint. Thanks!

My suspicion is that the Head component of the Document (import { Head } from 'next/document') and the Head component used in the page (import Head from 'next/head') might be completely separate and don’t “communicate” with each other, each doing their own thing twice.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 36 (10 by maintainers)

Most upvoted comments

I have the same issue. I set my meta viewport in _document.js. Still a second meta viewport is added:

<meta name="viewport" content="width=device-width"/>

I do not set it myself.

OK, here we go… As suspected earlier I finally worked it out.

Apparently, the correct way of using the two different (!) Head components is to prepare the meta tags etc. only in the page component or other components, but not in the _document.js file. In the _document only include it from next/document like <Head /> without any children.

To clarify…

// pages/_document.tsx

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

class MyDocument extends Document {
	public render() {
		return (
			<html lang="en">
				<Head /> // Do not add any children here!
				<body>
					<Main />
					<NextScript />
				</body>
			</html>
		);
	}
}

export default MyDocument;
// pages/examplepage.tsx

import React from 'react';
import Head from 'next/head'; // We import `Head` from `next/head `!
import Layout from '../components/layout';

class ExamplePage extends React.Component {
	render() {
		return (
			<Layout>
				<Head>
					<title>Example page</title>
					<meta name="description" content="Example page description" />
				</Head>

				<h1>Example page</h1>
			</Layout>
		);
	}
}

export default ExamplePage;

And then in the Layout component you can define default meta tags and headers, but not in the _document itself.

I was used to the way react-helmet works. There you can set defaults at top level and override/add values in children, but you always use the same component. Here we use two different components with the same name, which, I guess, caused the confusion.

I think this is still a problem. We have to have some things in our document.js <Head> which will “push down” all other tags in the <head>. The result is that the charSet meta is too far down the document according to things like W3 validator. There is no solution for this currently. As we have seen, putting the meta on top of the mandatory scripts in document.js is not a solution.

A solution I found for this was to leave the _document as is, but add the viewport metadata in a next/head component inside each page. This will cause the “page” viewport metadata to override the default one set by _document and leaves the charset metadata (set by _document) at the very top.

I ended up creating a custom Head component (that uses next/head) which already sets the viewport metadata (so I don’t have to repeat it on every page).

I’m using the SSG of Next.js, so maybe this doesn’t apply for SSR pages, don’t know. Hope it helps 👍

The way I solved this is, I created a CustomHead extending head from next/document and use it in my _document.tsx.

DocumentHead.tsx

import React from "react";
import { Head } from "next/document";

function dedupeHead(elems: React.ReactElement<any, string>[]) {
  const result: React.ReactElement[] = [],
    mapper: { [key: string]: number } = {};

  if (elems) {
    for (let i = 0, len = elems.length; i < len; i++) {
      const elem = elems[i],
        type = elem.type,
        props = elem.props;

      /** Dedupe */
      switch (type) {
        case "meta":
          let key = props.itemprop || props.property || props.name;

          if (key) {
            if (Object.prototype.hasOwnProperty.call(mapper, key)) {
              // This meta is already in the result,
              // Replace the one in result with this
              const dupeMetaIdx = mapper[key];
              result[dupeMetaIdx] = elem;
            } else {
              // Save the elem's index in result.
              mapper[key] = result.push(elem) - 1;
            }
          } else {
            // Do not handle deduping for unknown case
            result.push(elem);
          }

          break;
        default:
          // Do not handle deduping for unknown case
          result.push(elem);
          break;
      }
    }
  }

  return result;
}

class DocumentHead extends Head {
  render() {
    this.context.head = dedupeHead(this.context.head);
    return super.render();
  }
}

export default DocumentHead;

next/head should be used in _app / pages.

_document is only for the initial document HTML and if you’re going to override on the page level it won’t work as we simply won’t know about it on the client-side as _document is server-side only.

@gothy You might be right, it’s probably best to get the opinion of the Next.js team, what the intended usage is.

If we are supposed to define defaults in the _document.js, which makes sense, then it looks like a bug indeed. If one is supposed to prepare all the head tags outside _document.js (as described in my previous comment), then it should be made clearer and maybe the Head component of next/head should not even accept children.

Is there a way to prevent the extra addition of the charSet meta tag in the lib/head.js file, even explicitly (for instance, by using a flag)? In general, its usage is problematic: the tag is inserted way too low in the head, therefore causing site validation to throw errors. This seems to be problematic, even if head is added to the _app.js file.

I’ve also struggled with this one this week, and couldn’t find a solution that was satisfactory. @chozzz’s comment led me to what I was looking for, but I simplified the custom head to only remove the duplicate charset since that is was the only duplicated tag.

In _document:

class DocumentHead extends Head {
    render() {
        this.context.head = this.context.head.filter(item => !item.props?.charSet);
        return super.render();
    }
}

Use this DocumentHead component instead of Next’s Head component (the next/document version, of course). From here you simply need to add the charset tag as the first child of DocumentHead and this ensures it appears as close to the document start as possible:

render() {
        return (
            <Html lang="en">
                <DocumentHead>
                    <meta charSet="utf-8" />
                    ... etc

It seems clear that either charset should not be provided by default or there should be support for opting out of using it.

maybe next/head should not have the default meta, like viewport and charset

as overwrite in every page is not a good idea

Also seeing a duplicate meta viewport overriding the one I specify:

image

Adding an example of what @rscharfer is referring to:

_document.js

<Html>
  <Head>
    <meta charSet="utf-8" /> {/* Trying to add this at the very top of <head> */}
    {/* scripts, RSS feed etc. */}
  </Head>
</Html>

This will lead to duplicate meta charset tags.

And without adding the tag explicitly, Next will add it after your custom tags, which in this example would be way too far down. Adding the tag in a page component doesn’t work either; Next will append it.

As of next.js 12 - I no longer use my solution above. Adding key props to the meta tags solve the issue for me.

My experience was, if I remember correctly now, as soon as I start adding defaults in the _document head, I end up with duplicate meta tags.

@gothy I also wanted to follow the recommendation to set charSet as far at the top as possible. This does not seem to be guaranteed if you rely on Next’s defaults.

My solution (workaround?) is, as described above, do not set any defaults in the _document head, only in pages etc. For example, I use a Layout component, used by all pages and I set my default meta tags there and override them in individual pages.