The Goal: I have a Next JS website with lots of pages. Some pages will have specific OG Share images for that page for Facebook etc. but some won't have specific images and will just use a generic or globally set share image.
The Problem: Setting a global share image within _app.js works great and gives every page a share image. Setting a share image for a specific page also works and adds a OG Image tag in Head
. The problem now is there are two tags for an image, the global one and page specific one. Obviously Facebook doesn't know which one is best and just uses the first (global) one.
Possible Solutions:
Head
.Would love know if anyone has had the same issue and what you did!
To prevent duplicate tags, give each meta tag a key
as explained here in the documentation. When you do this, Next will prioritize them as your pages load and only include the one from the page, or if none exists on the page with that key, then it will fall back to the one in _app.js
.
Consider the following pages:
// pages/_app.js
import Head from 'next/head'
function MyApp({ Component, pageProps }) {
return (
<div>
<Head>
<meta property="og:title" content="Our Company Website" key="title" />
</Head>
<Component {...pageProps} />
</div>
)
}
// pages/about.js
import Head from 'next/head'
export default function AboutPage() {
return (
<div>
<Head>
<meta property="og:title" content="About Us" key="title" />
</Head>
<p>Learn about us</p>
</div>
)
}
// pages/contact.js
import Head from 'next/head'
export default function ContactPage() {
return (
<div>
<p>Send us an email</p>
</div>
)
}
In the above structure, the "contact" page will fallback to and show the "Our Company Website" meta tag found in _app.js
because it does not have a meta tag of its own with the same key but the "about" page will have the "About Us" meta tag because it has the title key meta tag which will take priority over the one in _app.js
.