Generating Open Graph Images at Build Time

When someone shares a link in Slack, LinkedIn or a messaging app, the platform fetches the page's og:image and shows it as a preview. Sites that set one generic image for every page get a wall of identical cards; sites that set none get a bare link that few people click. A unique card per page — the title, section and brand on a consistent background — is noticeably more clickable, and on a static site it can be generated during the build with no server at all.

This guide renders cards with Satori and resvg, integrates them with Astro, Hugo and Eleventy, and keeps the build fast with caching. It sits under Image Optimization Pipelines in Astro because the same concerns apply: file size, format, caching and build time.

Prerequisites

  • Node.js 20 or later in the build.
  • satori and @resvg/resvg-js: npm install satori @resvg/resvg-js.
  • One or two font files in TTF, OTF or WOFF format (Satori does not read WOFF2).
  • Page titles and descriptions available as data at build time.

The Rendering Pipeline

Satori takes a tree of elements — written as JSX or as plain objects — with a subset of CSS flexbox styling, lays out text with the fonts you give it, and returns an SVG string. resvg rasterises that SVG to PNG. Neither needs a browser.

Open Graph card generation pipeline Page data flows into a card template, then Satori produces SVG, resvg produces a 1200 by 630 PNG, and the file is written to the output folder. A cache check on a hash of the title and template skips rendering when the card already exists. From page data to og:image page data title, section cache check hash exists? Satori JSX → SVG resvg SVG → PNG dist/og/*.png 1200 × 630 cache hit: copy existing PNG, skip rendering about 45 ms per rendered card on a CI runner; about 1 ms per cache hit
No headless browser is involved, so the step runs anywhere Node.js runs.

A Minimal Card Renderer

This module renders one card and is independent of the site generator:

// scripts/og-card.mjs
import satori from 'satori';
import { Resvg } from '@resvg/resvg-js';
import { readFile } from 'node:fs/promises';

const fontRegular = await readFile('./src/fonts/Inter-Regular.ttf');
const fontBold = await readFile('./src/fonts/Inter-Bold.ttf');

export async function renderCard({ title, section }) {
  const svg = await satori(
    {
      type: 'div',
      props: {
        style: { width: 1200, height: 630, display: 'flex', flexDirection: 'column',
                 justifyContent: 'space-between', padding: 72,
                 background: '#0f172a', color: '#f8fafc', fontFamily: 'Inter' },
        children: [
          { type: 'div', props: { style: { fontSize: 30, color: '#93c5fd' }, children: section } },
          { type: 'div', props: { style: { fontSize: 64, fontWeight: 700, lineHeight: 1.15 }, children: title } },
          { type: 'div', props: { style: { fontSize: 28 }, children: 'example.com' } },
        ],
      },
    },
    { width: 1200, height: 630,
      fonts: [{ name: 'Inter', data: fontRegular, weight: 400 },
              { name: 'Inter', data: fontBold, weight: 700 }] },
  );
  return new Resvg(svg).render().asPng();
}

Satori supports flexbox, not grid, and a subset of CSS properties; the Vercel OG playground is a quick way to design a layout before moving it into the build.

Integrating With Your Generator

Astro. Add an endpoint that generates one PNG per content entry. With getStaticPaths, Astro calls it once per page during astro build and writes the result to dist/og/<slug>.png:

// src/pages/og/[...slug].png.ts
import { getCollection } from 'astro:content';
import { renderCard } from '../../../scripts/og-card.mjs';

export async function getStaticPaths() {
  const docs = await getCollection('docs');
  return docs.map((d) => ({ params: { slug: d.id }, props: { title: d.data.title, section: d.data.section } }));
}

export async function GET({ props }) {
  return new Response(await renderCard(props), { headers: { 'Content-Type': 'image/png' } });
}

The layout then sets <meta property="og:image" content={new URL(/og/${slug}.png, Astro.site)} />.

Eleventy. Use a JavaScript template with pagination over a collection and permalink: /og/{{ page.fileSlug }}.png, returning the PNG buffer from render. Eleventy writes binary output from JavaScript templates as-is.

Hugo. Hugo cannot run Node.js inside a build, so generate cards in a separate step before hugo, reading front matter with a small script, writing into static/og/, and referencing /og/{{ .File.ContentBaseName }}.png in the head partial. Alternatively, Hugo's own images.Text filter can draw a title onto a background image with no extra tooling, at the cost of less layout control.

Tags That Platforms Read

Every page needs absolute URLs and a few companion tags:

<meta property="og:title" content="Generating Open Graph Images at Build Time">
<meta property="og:image" content="https://example.com/og/generating-open-graph-images.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Card showing the article title">
<meta name="twitter:card" content="summary_large_image">

Declaring width and height lets some platforms render the preview on first share instead of fetching the image first. The alt text makes the preview accessible where the platform supports it.

Safe area on a 1200 by 630 card A 1200 by 630 card outline scaled down. A centered square region of 630 by 630 is marked as the area that survives square crops. The title is placed inside a 72 pixel margin and within the central area; the logo sits bottom left and may be cropped on square previews. Where text survives cropping Page title here, up to three lines logo 1200 × 630 square crop 630 × 630 72 px margin
Keep the title centred and short enough to stay inside the square crop some apps use.

Keeping the Build Fast and the Files Small

Rendering takes 30 to 80 milliseconds per card, which is two minutes on a 2,000-page site if every build renders every card. Cache instead: compute a hash of the card's inputs (title, section and a template version string), write cards to a cache folder named by that hash, and copy from the cache when it exists. Persist that folder between CI runs, as with any other build cache; see Incremental Builds and Build Caching for SSGs.

For file size, flat colours and text compress very well as PNG. A typical generated card is 40 to 90 KB. If you add a photograph or gradient background, run the PNG through oxipng or switch to JPEG at quality 85, and stay under about 300 KB — some platforms silently ignore larger images. These files are never loaded by your own pages, so they do not affect Core Web Vitals, but they are served from your CDN every time a link is unfurled, and should get a long cache lifetime.

Build time spent on card generation by method For 2000 pages: Puppeteer screenshots take 14 minutes, Satori and resvg without a cache take 1.5 minutes, and Satori with a warm cache takes 4 seconds. Card generation time, 2,000 pages, CI runner Puppeteer screenshots 14 min Satori + resvg, cold 1.5 min Satori + resvg, warm cache 4 s warm cache: only pages whose title or template changed are rendered
Dropping the headless browser removed most of the cost; the cache removed the rest.

Designing a Card Template That Scales

A template that looks good with one sample title often fails on the real set of pages. Before rolling it out, render every card once and look at the extremes: the shortest title, the longest, titles with code in backticks, and titles in any other languages the site publishes.

A few rules keep the template robust:

  • Scale the font size by title length. For example 72 pixels up to 40 characters, 60 up to 70, and 52 beyond. Satori has no automatic text fitting, so compute the size before rendering.
  • Strip Markdown from titles. Backticks, asterisks and HTML entities should be removed or decoded, or they appear literally on the card.
  • Use the section or category as a second line. It gives context when the title alone is ambiguous, and it lets a reader recognise which part of the site the link belongs to.
  • Keep brand elements small. A logo in one corner is enough; the title is what readers read in a crowded feed.
  • Check contrast. Previews are often shown small, so use a contrast ratio well above the 4.5:1 minimum for body text.

Version the template with a constant that feeds into the cache hash, so a design change regenerates every card on the next build rather than leaving a mix of old and new.

Testing Previews

Before relying on the cards, check them the way platforms see them. The Facebook Sharing Debugger and LinkedIn Post Inspector fetch your page and show the preview they would render, and they also refresh the platform's cache after you change an image. For Slack and Discord, paste the URL into a private channel. A quick automated check in CI is simpler still: for a sample of built pages, parse the og:image URL, confirm the file exists in the output directory, and confirm its dimensions are 1200 by 630.

Measured Impact

A documentation site with 1,400 pages replaced a single site-wide preview image with generated cards. Click-through from links shared in the project's community Slack and on LinkedIn rose by about a third over the following two months, based on UTM-tagged referrals. The cached card step added four seconds to a typical CI build and 1.5 minutes to a cold build.

Pitfalls & Rollback

  • Relative og:image URLs. Platforms need absolute URLs including the scheme.
  • WOFF2 fonts. Satori cannot read them; ship TTF or WOFF copies for the build.
  • Long titles. Clamp to three lines or reduce the font size by title length, or text overflows the card.
  • Non-Latin scripts. Load a font that covers them, or Satori renders empty boxes.
  • Rollback: point og:image back at a single static file and remove the generation step.

Conclusion

Per-page Open Graph cards make shared links recognisable and more clickable, and a static site can produce them at build time without a browser. Satori lays out a card from page data, resvg renders it to PNG, a hash-based cache keeps builds fast, and a handful of meta tags with absolute URLs make platforms use it. The whole step costs seconds on an incremental build.

FAQ

What size should an Open Graph image be?

1200 by 630 pixels is the standard that works across Facebook, LinkedIn, Slack, Discord and X large cards. Keep important text inside a central safe area, because some platforms crop the edges or show the image at a square aspect ratio.

Should Open Graph images be PNG or JPEG?

PNG is best for text-heavy generated cards because it keeps edges sharp, and generated cards with flat colours compress well. Use JPEG only if the card includes a photograph. Keep each file under about 300 KB; some platforms ignore larger images.

Why use Satori instead of a headless browser?

Satori converts HTML and CSS written as JSX into SVG without a browser, and resvg turns the SVG into PNG. Together they render a card in tens of milliseconds, versus hundreds of milliseconds per page with Puppeteer, and they need no Chromium download in CI.

Do generated Open Graph images slow down the build?

They add work proportional to the number of pages, typically 30 to 80 milliseconds per card. Cache cards on a hash of the title and template so unchanged pages skip rendering, and the cost on incremental builds is close to zero.