Next.jsMedium

How do you generate dynamic metadata (Open Graph, Twitter cards)?

Export generateMetadata from the page to return data-driven title, description, openGraph and twitter fields, and add an opengraph-image.tsx (and optionally twitter-image.tsx) file in the route segment that returns an ImageResponse. Next.js generates the image per URL and adds the right og:image and twitter:image tags automatically.

Dynamic text metadata

generateMetadata({ params }) awaits params, loads the record and returns fields. Share the data call with the page through fetch memoization or a cached function.

Generated images

  • app/blog/[slug]/opengraph-image.tsx exports a default function returning new ImageResponse(<jsx/>, { width: 1200, height: 630 }) from next/og.
  • Export alt, size and contentType for the meta tags.
  • Since Next.js 16 the image function receives params as a Promise.
  • ImageResponse uses Satori: flexbox layout and a subset of CSS. Next.js 16.2 made it 2x to 20x faster, expanded CSS and SVG support, and changed the default font to Geist Sans.
  • Load custom fonts with readFile (Node.js) and pass them in fonts.
  • Images are generated at build time when possible and cached.

Multiple images per page

generateImageMetadata returns several image variants; the image function then receives id as a Promise in Next.js 16.

Testing

Share links in platform validators (LinkedIn Post Inspector, Facebook Sharing Debugger) or use an OG preview tool. Ensure metadataBase is set so image URLs are absolute.

Code example

tsx
1// app/blog/[slug]/opengraph-image.tsx
2import { ImageResponse } from "next/og";
3import { getPost } from "@/lib/posts";
4
5export const alt = "Blog post cover";
6export const size = { width: 1200, height: 630 };
7export const contentType = "image/png";
8
9export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
10 const { slug } = await params; // a Promise since Next.js 16
11 const post = await getPost(slug);
12
13 return new ImageResponse(
14 (
15 <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", width: "100%", height: "100%", padding: 80, background: "#0b1020", color: "white" }}>
16 <div style={{ fontSize: 28, opacity: 0.7 }}>acme.dev/blog</div>
17 <div style={{ fontSize: 64, fontWeight: 700 }}>{post?.title ?? "Acme Blog"}</div>
18 </div>
19 ),
20 size
21 );
22}
23
24// app/blog/[slug]/page.tsx
25// export async function generateMetadata({ params }) {
26// const { slug } = await params; const post = await getPost(slug);
27// return { title: post.title, description: post.excerpt,
28// twitter: { card: "summary_large_image" } }; // og:image added from opengraph-image.tsx
29// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app