[SOLVED] Next JS Global and Page Specific Share Images

Issue

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:

  1. Currently I have removed the global tags and will be setting each page individually which isn’t ideal. It would be nice to know a page will always have a share image as a fallback.
  2. When adding a page specific image tag overwrite/remove the globally set one.
  3. Position the page specific image tag above the global tag in Head.
  4. Somehow only add the global tag if a page specific tag isn’t found.

Would love know if anyone has had the same issue and what you did!

Solution

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.

Answered By – I'm Joe Too

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.