Next.js · Middle · Question 59 of 75

How do you generate a dynamic Open Graph image (e.g. with the post title) in code?

// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og'

export default async function Image({ params }) {
  const { slug } = await params
  return new ImageResponse(<div style={{ fontSize: 64 }}>{slug}</div>)
}

Explanation

ImageResponse turns JSX and a subset of CSS (flexbox) into a PNG. By default the image is generated at build time and cached unless it uses request-time APIs.

Further reading

Problem with a question

Next.js · Middle · question 59

Test yourself

Take the Next.js · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz