Nextjs Fundamentals · Optimization & Metadata

Generating OG images

`ImageResponse`

Generating OG images

An Open Graph (OG) image is the preview social platforms show for a link. Next.js generates one with the ImageResponse constructor from next/og, which renders JSX and CSS to an image.

The file convention is opengraph-image.tsx. Default-export a function that returns a new ImageResponse, and export size, contentType, and alt:

import { ImageResponse } from 'next/og';

export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

export default function Image() {
  return new ImageResponse(
    <div
      style={{
        fontSize: 128,
        background: 'white',
        width: '100%',
        height: '100%',
        display: 'flex',
      }}
    >
      My Blog
    </div>,
  );
}

Place the file next to a page.tsx and it applies to that route; place it at the root of app and it applies everywhere, with more specific files taking precedence. Because the function can be async and read params, you can generate a unique image per post.

ImageResponse supports flexbox and a subset of CSS — not every property works.

In short: add an opengraph-image.tsx that returns new ImageResponse(...) to generate a social image.

You are about to answer a short quiz on ImageResponse.

  1. You import the ImageResponse constructor from ___.
  2. The opengraph-image file convention generates a social preview image for a route.
  3. ImageResponse supports the full range of CSS, including CSS grid.
  4. An opengraph-image file default-exports a function that returns a new ___.
  5. Because the image function can read params, you can generate a unique OG image per post.