I’m developing my website with next.js.
My Question
The code below is in _document.js
Head component. These are root meta tags.
JavaScript
x
3
1
<meta name="description" content="~~~"/>
2
<meta name="keywords" content="~~~"/>
3
When pages are dynamically created, these tags are created and inserted in Item.js
.
JavaScript
1
3
1
<meta name="description" content={item.product_description}/>
2
<meta name="description" content={item.brand_name}/>
3
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
.
JavaScript
1
11
11
1
useEffect(() => {
2
const description = document.getElementsByName('description');
3
const keywords = document.getElementsByName('keywords');
4
description[0].content = item.product_description;
5
keywords[0].content = item.brand_name;
6
return () => {
7
description[0].content = '~~~';
8
keywords[0].content = '~~~';
9
}
10
}, [])
11
But this way seems wrong. How can I avoid duplicated meta tags more clearly?
I want to get my meta tags for latest one.
Advertisement
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.