Adding Social Cards Images to your meta tags in Next.Js

In the previous post I explained how to use Vercel’s Image OG to generate images through API requests, I used it to dynamically generate thumbnails for blog posts. Now, in this last part I’ll quickly explain how to add the meta tags to your website and make sure they display properly.

Adding meta tags

In Next.js we put our meta tags inside the inbuilt Head component. We just need to import it in our component and put the meta tags in between like this :

import Head from "next/head";
 
const Component:FC<props> = ({ children }) => {
return (<Head>
<meta name="Author" content="Pedro Coelho" />
<meta name="Publisher" content="Pedro Coelho" />
</Head>)
};

In my case I’ve decided to put the Head component inside a Layout component, which carries layout that is consistent throughout all the pages of my blog, I added an ogImageData prop to the component that takes a title and an emoji that will later be passed to the OG API. Here is an example with the image meta tags I use :

import React, {FC} from "react";
import Head from "next/head";
import styles from "../styles/Layout.module.scss";
import Header from "./Header";
 
interface props {
  children: React.ReactNode;
  ogImageData?: {
    title:string,
    emoji?:string,
  },
}
 
const Layout:FC<props> = ({ children, ogImageData}) => {
  return (
    <div className={styles.container}>
      <Head>
        <meta
          property="og:image"
          content={imgUrl}
        />
        <meta name='twitter:image'  content={imgUrl} />
      </Head>
      <Header></Header>
      {children}
    </div>
  );
};
 
export default Layout;

As you can see we need to define the image’s URL, in the previous part we created our api endpoint at ‘api/og’ therefore we should specify the URL accordingly:

const imgUrl =
  `${process.env.NODE_ENV != 'development' ?
  'https://www.pedrocoelhodev.com/' : 'http://localhost:3000/'}`  +
  'api/og?title=' + ogImageData?.title ?? 'Pedro Coelho'
  + `${ogImageData?.emoji ? '&emoji=' + ogImageData.emoji : ''}`;

I added a condition to check the environment I’m running the app on, using localhost if in the development environment. I also added checks and fallbacks in case no title or no emoji was provided.

Now, we just need to pass the ogImageData props whenever the Layout component is used, in my post component it is used like this:

<Layout ogImageData={{
      title: post.title,
      emoji: post.emoji,
    }}
>
/* post data */
</Layout>

If we deploy our website now everything should be working, however if you try to post a link on social media you might not see your image yet, this can happen because the social media network’s crawler might have already cached and older version of your website. To ensure your social media cards are displaying you can check the network’s own social media card debug tools: