Ad

How To Avoid Duplicated Meta Tags?

- 1 answer

I'm developing my website with next.js.

My Question

The code below is in _document.js Head component. These are root meta tags.

<meta name="description" content="~~~"/>
<meta name="keywords" content="~~~"/>

When pages are dynamically created, these tags are created and inserted in Item.js.

<meta name="description" content={item.product_description}/>
<meta name="description" content={item.brand_name}/>

To avoid duplication of meta tags, I inserted some key="" values in meta refer to Next.js docs, but it didn't work. So, I forced to change contents by using useEffect.

useEffect(() => {
    const description = document.getElementsByName('description');
    const keywords = document.getElementsByName('keywords');
    description[0].content = item.product_description;
    keywords[0].content = item.brand_name;
    return () => {
        description[0].content = '~~~';
        keywords[0].content = '~~~';
    }
}, [])

But this way seems wrong. How can I avoid duplicated meta tags more clearly?

I want to get my meta tags for latest one.

enter image description here

Ad

Answer

Meta tags added to the custom _document cannot be deduped.

To solve this constraint, you should set the default meta tags in your _app inside next/head (where they can be deduped), and overwrite them when needed in your pages.

Ad
source: stackoverflow.com
Ad