Add Open Graph in Next.js

Feb-11, 2025 · 8min

change language

Learn how to add Open Graph images in a Next.js project, including static generation of OG images, using the satori library, configuring route handlers, and SEO optimization.

Add OG Image

Official documentation recommends the following methods:

  • Use opengraph-image.jpg as OG image in the related routes
  • Use opengraph-image.js to dynamically generate

But neither of these methods meets my needs, I need the entire website to be as static as possible, and these OG images can be generated through some configurations during the build.

The current idea is to use Next.js's Route Handlers to generate OG images during the build.

import { ImageResponse } from "next/og";

export async function generateStaticParams() {
  const { posts } = await getPosts();

  // Get the related information of posts
  return posts.map((post) => ({
    slug: `${post.pageName}.png`,
  }));
}

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ slug: string }> },
) {
  const { slug } = await params;

  // Return the corresponding png image
  return new ImageResponse(
    <div>
      <h1>{slug.slice(0, -4)}</h1>
    </div>
  );
}

Note that the path returned here adds the .png suffix to avoid the static site from being unable to distinguish the response type.

Use generateStaticParams to get the related information for generating OG images.

satori is a library for generating OG images, which can generate SVG and PNG images.

vercel's OG image generation documentation

orcascan's OG image verification tool

Brief information

  • Static generate OG Image
    • Use [og/[slug]/route.tsx] to change the slug to [post.pageName].png
    • generateStaticParams to generate OG images for posts
    • [remark-mdx-slug] to get the slug remark-mdx-slug.ts
    • remark-mdx-formatter to configure openGraph to use [/og/${post.pageName}.png] as the OG image, see next.config.ts, remark-mdx-formatter.ts file