Search code examples
next.jsseometadatanext.js13

How to add twitter metatags dynamically in Next.js 13


I am using Next.js 13 and using the generateMetaData function for dynamic metadata works for openGraph, but how to do it for Twitter meta tags?

export async function generateMetadata( {params, searchParams}: Props, parent?: ResolvingMetadata): Promise<Metadata> {
  return {
    openGraph: {
      type: "website",
      url: '',
      title: '',
      description: '',
      image: '',
    }
  }
}

For instance, the HTML output needs to be:

  <meta property="twitter:card" content="summary_large_image" />
  <meta property="twitter:url" content={url} />
  <meta property="twitter:title" content={ogTitle} />
  <meta property="twitter:description" content={ogDescription} />
  <meta property="twitter:image" content={ogImage} />

Solution

  • You need to do something very similar for twitter:

      twitter: {
        card: "summary_large_image",
        title: "Your title",
        description: "Your description",
        creator: "@author_name",
        images: ["you_url_here"],
      },
    

    Don't forget that the recommended dimensions are 1200x630px.

    More info here: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#twitter

    Also if you end up having issues with the title / description being rendered but not the image, you might want to use this way to specify the information for the image:

      twitter: {
        card: "summary_large_image",
        title: "Your title",
        description: "Your description",
        creator: "@author_here",
        images: [
          {
            url: "you_url_here",
            blurDataURL: "you_blured_url_here",
            width: 1200,
            height: 630,
            alt: "Your alt text",
          },
        ],
      },