Skip to content
Shareglow

Guides · Updated

Dynamic Open Graph images for a Next.js app

A blog post or product page shared with your generic site logo gets fewer clicks than one that shows its own title. Next.js has two built-in ways to give every route its own image: point the metadata at an image URL, or generate the image in an opengraph-image file next to the page. This guide covers both for the App Router, plus how to check the result the way a crawler sees it.

First, set metadataBase

Crawlers need absolute image URLs. Set metadataBase once in the root layout, and Next.js turns relative image paths in your metadata into absolute ones. Without it, Next.js falls back to a default origin that is often wrong in production.

app/layout.tsx
// app/layout.tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  metadataBase: new URL("https://example.com"),
  openGraph: { siteName: "Example" },
  twitter: { card: "summary_large_image" },
};

Option 1: generateMetadata with an image URL

If your images already exist (uploaded by an editor, stored in a CMS, or rendered by an image service), return their URL from generateMetadata. In Next.js 16 params is a Promise, so await it before you use it.

app/blog/[slug]/page.tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { getPost } from "@/lib/posts";

export async function generateMetadata(
  { params }: { params: Promise<{ slug: string }> },
): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      type: "article",
      images: [{ url: post.coverUrl, width: 1200, height: 630, alt: post.title }],
    },
  };
}

Child segments override the openGraph object of their parents rather than merging into it, so repeat any field you need (such as siteName) on pages that set their own openGraph.

Check your own link in seconds, free

Option 2: the opengraph-image file convention

To draw the image from the page's own data, add an opengraph-image.tsx file to the route segment. Next.js serves it as an image route and adds the og:image, og:image:width, og:image:height, og:image:type and og:image:alt tags for you. ImageResponse from next/og turns JSX and inline styles into a PNG.

app/blog/[slug]/opengraph-image.tsx
// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from "next/og";
import { getPost } from "@/lib/posts";

export const alt = "Blog post cover";
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";

export default async function Image(
  { params }: { params: Promise<{ slug: string }> },
) {
  const { slug } = await params;
  const post = await getPost(slug);
  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          padding: 80,
          background: "#0b1020",
          color: "white",
        }}
      >
        <div style={{ fontSize: 64, fontWeight: 700 }}>{post.title}</div>
        <div style={{ fontSize: 32, opacity: 0.7, marginTop: 24 }}>example.com</div>
      </div>
    ),
    { ...size },
  );
}

Add a twitter-image.tsx file with the same code if you want a separate image for X; otherwise X uses og:image through its fallback. The image is generated at build time for static routes and cached, and on request for dynamic ones.

Layout rules that catch people out

Test it like a crawler

Your browser is not a good test: it runs JavaScript and caches aggressively. After you deploy, request the page with a crawler user agent and look for the tags in the raw HTML:

Terminal
curl -s -A "Twitterbot/1.0" https://example.com/blog/hello | grep -o '<meta[^>]*og:[^>]*>'

Then open the og:image URL directly to make sure it renders, and run the page through the free OG scanner and preview simulator to see the card on 30 platforms. If a platform still shows an older card, follow the cache refresh guide.

When to hand it off

Generating images in your app is free to start, but every template change means a code change and a redeploy, and every new script or brand colour is yours to maintain. If you would rather design templates visually and get a cached image URL per page, Shareglow's OG image generator renders them on the edge and the Next.js fix page shows the metadata snippet to wire it in.

FAQ

Common questions

Do I need both opengraph-image and generateMetadata?

No. Use opengraph-image.tsx to generate the image from code, or return an image URL from generateMetadata. Pick one per route.

Why is my og:image URL relative or pointing at localhost?

metadataBase is missing or wrong. Set it in the root layout to your production origin.