• Homeright arrow
  • Blogright arrow
  • How to add OpenGraph Metadata in Next.js
Feature

How to add OpenGraph Metadata in Next.js

Ensuring proper metadata for enhanced social sharing and SEO is crucial when building modern web applications. Open Graph (OG) meta tags enable control over how web pages are represented when shared on social media platforms, such as Facebook, Twitter, and LinkedIn. In Next.js, which is designed for optimal web performance, integrating Open Graph meta tags has become even easier with the App Router introduced in Next.js.

By utilizing the metadata API within the app/ directory, developers can declaratively define Open Graph tags globally or per page. This new approach simplifies the process, allowing Next.js to automatically inject the appropriate Open Graph meta tags into the page's <head>. This ensures that your content is well-formatted for social sharing, driving engagement and visibility across platforms.

In this guide, we will walk through how to add Open Graph tags in a Next.js app using the new App Router structure, enabling you to provide detailed, SEO-friendly previews when your pages are shared.

What is OpenGraph?

Open Graph protocol allows web pages to become rich objects on social media platforms. It enables websites to control how their content is displayed when shared on platforms like Facebook, Twitter, LinkedIn, etc. Using Open Graph metadata, website owners can specify the title, description, image, and other elements that appear in the link preview when someone shares a URL from their site.

Adding OpenGraph in Next.js

Adding OpenGraph (OG) meta tags in a Next.js app using the App Router (app/ directory) is very easy. Open Graph tags are HTML meta tags that define how URLs are represented on social media platforms. You can configure these tags by using React’s head component in the relevant layout or page.

Here's how you can add Open Graph tags in your Next.js app with the App Router:

Global OpenGraph Tags

In the Next.js app router, define meta tags in the layout.js file if you want the Open Graph tags to be present across all pages, or you can add them inside a specific page component for page-specific metadata.

// app/layout.js
export const metadata = {
openGraph: {
title: 'Next.js',
description: 'The React Framework for the Web',
url: 'https://nextjs.org',
siteName: 'Next.js',
images: [
{
url: 'https://nextjs.org/og.png', // Must be an absolute URL
width: 800,
height: 600,
},
{
url: 'https://nextjs.org/og-alt.png', // Must be an absolute URL
width: 1800,
height: 1600,
alt: 'My custom alt',
},
],
videos: [
{
url: 'https://nextjs.org/video.mp4', // Must be an absolute URL
width: 800,
height: 600,
},
],
audio: [
{
url: 'https://nextjs.org/audio.mp3', // Must be an absolute URL
},
],
locale: 'en_US',
type: 'website',
},
}

Example in a Page Component (Page-Specific Open Graph Tags)

If you want OpenGraph meta tags for specific pages, you can set them inside the page’s metadata field:

export const metadata = {
openGraph: {
title: 'About Page',
description: 'The React Framework for the Web',
url: 'https://nextjs.org',
siteName: 'Next.js',
images: [
{
url: 'https://nextjs.org/og.png', // Must be an absolute URL
width: 800,
height: 600,
},
{
url: 'https://nextjs.org/og-alt.png', // Must be an absolute URL
width: 1800,
height: 1600,
alt: 'My custom alt',
},
],
videos: [
{
url: 'https://nextjs.org/video.mp4', // Must be an absolute URL
width: 800,
height: 600,
},
],
audio: [
{
url: 'https://nextjs.org/audio.mp3', // Must be an absolute URL
},
],
locale: 'en_US',
type: 'website',
},
}

For more information on metadata, you can read these articles.

  1. How to Add Metadata to Your Next.js Application for SEO
  2. Creating Dynamic Metadata with Next.js


Add an OpenGraph Image

The OpenGraph image is useful for setting the images that appear on social networks and messaging apps when a user shares a link to your site. In the next js, it is a very straightforward process. We can use the routing method of Next.js  for this. There are two steps to set OpenGraph in the NextJS:

  • Using image files (.jpg, .png, .gif)
  • Using code to generate images (.js, .ts, .tsx)

Using image files (.jpg, .png, .gif)

To set an OpenGraph image file in Next.js, add the opengraph-image.(jpg|jpeg|png|gif) image in any route segment. This image will automatically generate the appropriate meta tags for your app's <head> element.

You can also include alt text for these images by adding an opengraph-image.alt.txt file, which contains the descriptive text for accessibility and SEO purposes.


Using code to generate images (.js, .ts, .tsx)

In addition to using static image files, you can programmatically generate images in Next.js using JavaScript, TypeScript, or TSX. This allows for more dynamic image creation, such as including custom data or content in images.  Create opengraph-image.js, opengraph-image.ts, or opengraph-image.tsx file at the route segment. This will export an OpenGraph image route that exports a default function. The easiest way to generate an image is to use the ImageResponse API from next/og.

import {ImageResponse} from "next/og";
// Route segment config
export const runtime = "edge";
// Image metadata
export const alt = "About Acme";
export const size = {
width: 1200,
height: 630,
};
export const contentType = "image/png";

// Image generation
export default async function Image() {


return new ImageResponse(
(
// ImageResponse JSX element
<div
style={{
fontSize: 128,
background: "white",
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
About Acme
</div>
),
// ImageResponse options
{
// For convenience, we can re-use the exported opengraph-image
// size config to also set the ImageResponse's width and height.
...size,
}
);
}


In Next.js, the default export function for generating images can receive an optional parameter object. This object contains the dynamic route parameters from the root segment to the segment where the openGraph-image is colocated. This allows you to generate images dynamically based on the route parameters.

Props:

params (optional): An object that holds the dynamic route parameters.

Example:

Let’s say you have a dynamic route like app/shop/[slug]. You can use the params object to generate an image based on the productId.

import { ImageResponse } from 'next/og';


export const size = {
width: 1200,
height: 630,
};


export default function ({ params }) {
const { shopID } = params; // Retrieve dynamic route parameter


return new ImageResponse(
(
<div
style={{
fontSize: 48,
color: 'white',
background: 'blue',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
Shop ID: {shopID }
</div>
),
{
// For convenience, we can re-use the exported opengraph-image
// size config to also set the ImageResponse's width and height.
...size,
}
);
}

In this example:

  • If your route is shop/[slug]/1, the params object will look like { Shop ID: “1” }, and the image generated will display "Shop ID: 1".
  • The params can be used to create dynamic OpenGraph images based on the URL's dynamic parameters.

In Next.js, you can configure the metadata for dynamically generated images by exporting the alt, size, and contentType variables from an open graph-image route. These properties help define image accessibility, dimensions, and MIME type for social sharing.

Config Options:

  • alt (string): Defines the alt text for the image.
  • size (object): Specifies the width and height of the image.
  • contentType (string): Sets the image MIME type (e.g., image/png).

Example: Configuring Image Metadata

Alt Text:

export const alt = 'My image alt text';
export default function Image() {
// Image generation logic
}

This will add the following to your <head>:

<meta property="og:image:alt" content="My image alt text" />

Size:

export const size = { width: 1200, height: 630 };
export default function Image() {
// Image generation logic
}


This will add the following to your <head>:

<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />

Content Type:

export const contentType = 'image/png';
export default function Image() {
// Image generation logic
}

This will add the following to your <head>:

<meta property="og:image:type" content="image/png" />

By exporting these variables, we can ensure that your dynamically generated images are fully optimized for social sharing with accurate metadata for accessibility and proper rendering.

That’s all. Following these steps, we can easily create OpenGraph metadata for our next.js app.


Conclusion

Adding an OpenGraph meta tag in a Next.js App Router is straightforward using the metadata object or the Head component. This enhances your page's social sharing capabilities by customizing how it appears on platforms like Facebook and Twitter. Whether you're working with static or dynamic pages, Next.js provides flexible options to ensure your content is displayed optimally across various social media platforms.

Keep exploring and enhancing your Next.js projects! Please do not hesitate to contact StaticMania with any questions or feedback. Happy coding!

footer-particlefooter-particlefooter-particlefooter-particlefooter-particle
back-to-top