Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 72 ยท Optimization and SEO

Generating Open Graph Images

Generate social preview images in Next.js with opengraph-image.tsx and ImageResponse, add twitter-image, icons and generateImageMetadata, and avoid the common limits.

When someone pastes your link into a chat or a social post, the app shows a preview card: a title, a short description and, most importantly, an image. That image comes from the og:image meta tag (Open Graph is the name of the convention). Pages with a good preview image get noticeably more clicks than pages with a grey placeholder, but nobody wants to design one image by hand for each of 500 blog posts.

Next.js solves this with image files that are generated by code. A file named opengraph-image.tsx returns an ImageResponse: you describe the picture with JSX and a small subset of CSS, and Next.js renders it to a PNG on the server. This lesson shows how to write one, how to give each page its own, how to produce several sizes, and which limits to expect. Next.js cannot run on this site, so the real files are read-only. The runnable examples are Node.js stand-ins: a text wrapper that lays out a title and builds an SVG card, and a model of the meta tags that Next.js adds for the files in a folder.

You met the file names in Templates and Other Special Files and the openGraph metadata object in Metadata and SEO. This lesson goes deeper into the generated version.

Three ways to get a preview image

A static file Drop opengraph-image.png in the folder.
A generated file opengraph-image.tsx returns an ImageResponse.
Metadata object Point openGraph.images at any URL.

Files in the folder are the simplest option.

1 / 2

The simplest case: a file next to the page

Put a file called opengraph-image.png (or .jpg, .gif) in a route folder and Next.js adds the matching <meta property="og:image"> tags for that route and everything below it. A twitter-image.png does the same for twitter:image. An alt text can sit in opengraph-image.alt.txt. Nothing else is needed: no code, no metadata object.

A file in app/ is the default for the whole site. A file in app/blog/ replaces it for blog pages. Because of that nesting, the most specific file wins, so you can have a generic card for the site and special cards where they matter.

Generating the image with code

When the image depends on data, such as a post title, name the file opengraph-image.tsx and export a default function. It may be async, and it receives the same params as the page.

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

export const alt = "Blog post preview";
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: "space-between",
          padding: 72,
          background: "linear-gradient(135deg, #0f172a, #1e3a8a)",
          color: "white",
        }}
      >
        <div style={{ fontSize: 32, opacity: 0.8 }}>example.com</div>
        <div style={{ fontSize: 68, fontWeight: 700, lineHeight: 1.15 }}>{post.title}</div>
        <div style={{ fontSize: 30, opacity: 0.8 }}>{post.author}</div>
      </div>
    ),
    { ...size }
  );
}

The exports alt, size and contentType are read by Next.js and turned into the og:image:alt, og:image:width, og:image:height and og:image:type tags. Use the standard 1200 by 630 pixels (a ratio of roughly 1.91 to 1) so that platforms do not crop your title.

The generated route is a normal request handler that Next.js builds into the page's metadata. Under the hood, ImageResponse uses a library that converts HTML and CSS to SVG and then to PNG, without launching a browser. That makes it fast, and it explains its limits:

  • Layout is flexbox only. Every element with more than one child needs display: "flex" (or display: "none"). There is no CSS grid.
  • Only a subset of CSS is supported: common typography, colors, gradients, borders, shadows, position: "absolute", transforms. Check the next/og documentation if a property does nothing.
  • Only a default font is bundled. To use your own, read a font file and pass it in the fonts option.
  • Total size of the JSX, fonts and images has a small limit (around 500 KB), so use a subsetted font and small images.
  • It is not React: no hooks, no event handlers, no Client Components, and no className with Tailwind unless you use the tw prop that ImageResponse supports.
TSX
// Loading a custom font (read-only)
const font = await fetch(new URL("./Inter-Bold.ttf", import.meta.url)).then((res) => res.arrayBuffer());

return new ImageResponse(<div style={{ fontFamily: "Inter" }}>Hello</div>, {
  ...size,
  fonts: [{ name: "Inter", data: font, style: "normal", weight: 700 }],
});

Text does not wrap the way you hope

A long title can overflow the card. ImageResponse does wrap text inside a flex container with a fixed width, but you still need to choose a font size that fits the longest title you have. A common trick is to shorten the title or pick the size from its length. The stand-in below does the same job in plain Node.js: it wraps a title to a line width, picks a font size from the length and builds an SVG card, which is the same final idea as ImageResponse without the JSX.

Node.js Lay out a title and build an SVG card

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

One image per page, or several per page

For a dynamic route you do not need any extra setup: the opengraph-image.tsx inside app/blog/[slug]/ runs for each slug and uses its params. Because the route is static when its data and params are known, Next.js can generate the images at build time along with generateStaticParams, and cache them.

If one page needs several images, for example a product with a gallery, or an icon in several sizes, use generateImageMetadata. It returns a list that describes each image, and the component receives the chosen id:

TSX
// app/products/[id]/opengraph-image.tsx (read-only)
import { ImageResponse } from "next/og";

export async function generateImageMetadata({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  return [
    { id: "wide", alt: `Product ${id}`, size: { width: 1200, height: 630 }, contentType: "image/png" },
    { id: "square", alt: `Product ${id}`, size: { width: 600, height: 600 }, contentType: "image/png" },
  ];
}

export default async function Image({ id, params }: { id: Promise<string | number>; params: Promise<{ id: string }> }) {
  const imageId = await id;
  const { id: productId } = await params;
  const size = imageId === "wide" ? { width: 1200, height: 630 } : { width: 600, height: 600 };
  return new ImageResponse(<div style={{ display: "flex", fontSize: 64 }}>Product {productId}</div>, size);
}

The image id becomes part of the URL, so each variant has its own address. The stand-in below models how a list of generated metadata turns into meta tags. It is an illustration of the mapping, not Next.js code, and a real URL also carries a content hash that lets caches keep the file for a long time.

Node.js From image metadata to meta tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Twitter cards, icons and the metadataBase

  • twitter-image.tsx works exactly like opengraph-image.tsx but sets the twitter:image tags. If you only have an Open Graph image, most platforms use it anyway, so add a separate file only when you want a different crop or text.
  • icon.tsx and apple-icon.tsx generate favicons the same way. Their size is small (for example 32 by 32), so the JSX is often a single letter or an emoji on a colored square.
  • Image URLs in meta tags must be absolute. Set metadataBase in the root layout (Metadata and SEO) so Next.js can build https://example.com/... from the relative route. A missing metadataBase is the number one reason a preview works locally and not in production.
  • To override the generated image for one page, set openGraph.images in that page's metadata, which takes precedence over the file.
  • A route handler for an image can read the database, so the image always matches the title. Pair it with revalidation so an edited title does not keep an old picture for days.

Testing a preview

  1. Open the image route directly in the browser. The URL appears in the page source, in the og:image meta tag.
  2. Check width, height and that the text is readable at small size: previews are often shown at a few hundred pixels wide.
  3. Social platforms cache previews. After changing an image, use the platform's own debugger or "refresh preview" tool, or add a version to the URL.
  4. Keep the file well under 8 MB (a few hundred KB is typical). Some platforms reject larger images.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a file named opengraph-image.tsx in app/blog/[slug]/ do?

    The file convention is picked up automatically. Next.js calls your function for each route and adds the matching meta tags without any import.
  2. 2. Which statement about ImageResponse is true?

    ImageResponse converts JSX and a CSS subset to an image without a browser. Layout is flexbox only and it is not a real React render.
  3. 3. When do you use generateImageMetadata?

    It returns a list describing each image (id, size, alt, type), and the image function receives the id to render the right variant.
  4. 4. Why might a preview image work locally but not after deploying?

    The og:image URL must be absolute. Setting metadataBase in the root layout lets Next.js turn the relative route into a full https URL.

Summary

  • A file opengraph-image.png is the zero-code option; opengraph-image.tsx generates the image from data using ImageResponse.
  • Export alt, size and contentType. Use 1200 by 630 pixels for Open Graph cards.
  • ImageResponse supports flexbox and a CSS subset, a small bundle size and custom fonts through the fonts option. It is not full React.
  • Use generateImageMetadata for several images per route, twitter-image for a separate Twitter card and icon.tsx for generated favicons.
  • Set metadataBase so image URLs are absolute, and remember that platforms cache previews.

Next: Fonts and Scripts