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.tsxexports a default function returningnew ImageResponse(<jsx/>, { width: 1200, height: 630 })fromnext/og.- Export
alt,sizeandcontentTypefor the meta tags. - Since Next.js 16 the image function receives
paramsas a Promise. ImageResponseuses 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 infonts. - 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
1// app/blog/[slug]/opengraph-image.tsx2import { ImageResponse } from "next/og";3import { getPost } from "@/lib/posts";45export const alt = "Blog post cover";6export const size = { width: 1200, height: 630 };7export const contentType = "image/png";89export default async function Image({ params }: { params: Promise<{ slug: string }> }) {10 const { slug } = await params; // a Promise since Next.js 1611 const post = await getPost(slug);1213 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 size21 );22}2324// app/blog/[slug]/page.tsx25// 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.tsx29// }
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.