🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
SEO••By Komal Nakrani

Astro OG Image Generation with Satori at Build Time

Generate an Astro OG image for every post at build time: a static endpoint with Satori and resvg, custom fonts, a getStaticPaths loop and meta tags that use it.

#Astro#OG Image#Open Graph#SEO#Satori

To generate an Astro OG image for every page, create a static endpoint such as src/pages/og/[...slug].png.ts, render a layout to SVG with Satori, convert it to PNG with @resvg/resvg-js, and return it from GET. With getStaticPaths() looping over your content collection, astro build writes one 1200 x 630 PNG per post into dist/, and your meta tags point at it.

No runtime service, no image editor, and the image always matches the post title because both come from the same frontmatter.

Key Takeaways

  • Satori turns a tree of elements with inline styles into SVG; resvg rasterizes that SVG to PNG. Both run at build time in Node.
  • A .png.ts file in src/pages/ is a static endpoint. Astro writes its output as a real .png file.
  • Satori needs font files as TTF, OTF or WOFF (not WOFF2), loaded as an ArrayBuffer or Buffer.
  • Every element with more than one child needs display: 'flex'. Satori supports a subset of CSS, mostly flexbox.
  • Point og:image at the generated path with an absolute URL built from Astro.site.

Why generate OG images

When someone shares a link on LinkedIn, Slack, Discord, iMessage or X, the platform fetches the page’s og:image and shows it as a preview card. A single generic image on every page makes all your links look identical. A per-page image with the title on it tells people what they’re about to read.

Designing those by hand doesn’t scale past a handful of posts. Generating them from the post data does: add a post, rebuild, and the image exists.

How the pieces fit

  1. Satori (from Vercel, open source) takes an element tree, similar to JSX, with inline styles, and returns an SVG string. It lays text out itself, which is why it needs the font files.
  2. resvg (@resvg/resvg-js) renders that SVG to a PNG buffer. Social platforms expect PNG or JPEG, not SVG.
  3. An Astro static endpoint runs that code once per path during the build and saves the response body to dist/.

Install both libraries:

npm install satori @resvg/resvg-js

You also need a font. Any TTF or OTF file works. The Fontsource packages include WOFF files, which Satori accepts:

npm install @fontsource/inter

The endpoint

// src/pages/og/[...slug].png.ts
import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection, type CollectionEntry } from 'astro:content';
import { readFile } from 'node:fs/promises';
import satori from 'satori';
import { Resvg } from '@resvg/resvg-js';

export const getStaticPaths = (async () => {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.id },
    props: { post },
  }));
}) satisfies GetStaticPaths;

const fontRegular = await readFile(
  'node_modules/@fontsource/inter/files/inter-latin-400-normal.woff',
);
const fontBold = await readFile(
  'node_modules/@fontsource/inter/files/inter-latin-700-normal.woff',
);

export const GET: APIRoute = async ({ props }) => {
  const { post } = props as { post: CollectionEntry<'blog'> };

  const svg = await satori(
    {
      type: 'div',
      props: {
        style: {
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          padding: '72px',
          background: '#0f172a',
          color: '#f8fafc',
          fontFamily: 'Inter',
        },
        children: [
          {
            type: 'div',
            props: {
              style: { fontSize: 28, color: '#94a3b8' },
              children: 'example.com/blog',
            },
          },
          {
            type: 'div',
            props: {
              style: { fontSize: 64, fontWeight: 700, lineHeight: 1.15 },
              children: post.data.title,
            },
          },
          {
            type: 'div',
            props: {
              style: { fontSize: 28, color: '#cbd5e1' },
              children: post.data.pubDate.toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
              }),
            },
          },
        ],
      },
    },
    {
      width: 1200,
      height: 630,
      fonts: [
        { name: 'Inter', data: fontRegular, weight: 400, style: 'normal' },
        { name: 'Inter', data: fontBold, weight: 700, style: 'normal' },
      ],
    },
  );

  const png = new Resvg(svg).render().asPng();

  return new Response(new Uint8Array(png), {
    headers: { 'Content-Type': 'image/png' },
  });
};

Run npm run build and look in dist/og/. Each post has a PNG named after its id, for example dist/og/my-first-post.png.

A few notes on the code:

  • [...slug] rest parameter. Collection ids can contain slashes when posts live in subfolders. A rest parameter handles both post and 2026/post.
  • Fonts read once. The top-level await readFile runs once per build, not once per image.
  • Plain objects instead of JSX. Satori accepts any object with type and props. This keeps the endpoint a .ts file with no React dependency. If you prefer JSX, rename to .tsx and add the React integration, or use the satori-html package to write the layout as an HTML string.
  • Static output only. In a static build, getStaticPaths() runs and every image is written to disk. In a site with on-demand rendering, add export const prerender = true to keep this endpoint static.

Point the meta tags at it

In the post layout or page, pass the generated path to your head component:

---
// src/pages/blog/[...slug].astro (frontmatter excerpt)
const ogImage = new URL(`/og/${post.id}.png`, Astro.site).href;
---
<meta property="og:image" content={ogImage} />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content={post.data.title} />
<meta name="twitter:card" content="summary_large_image" />

If you use a shared SEO component, pass image={'/og/' + post.id + '.png'} as a prop instead. The Astro meta tags component accepts exactly that.

og:image must be absolute. Platforms don’t resolve relative URLs, which is why site has to be set in astro.config.mjs.

Styling with Satori’s CSS subset

Satori implements a layout engine, not a browser. What works:

  • Flexbox: display: 'flex', flexDirection, justifyContent, alignItems, gap.
  • Box model: padding, margin, border, borderRadius, width, height.
  • Text: fontSize, fontWeight, lineHeight, letterSpacing, color, textAlign.
  • Backgrounds: solid colors, linear-gradient and radial-gradient, and backgroundImage with a data URI.
  • position: 'absolute' for overlays.

What doesn’t: CSS grid, calc() in most places, and stylesheets or class names (Tailwind classes need the tw prop, which Satori supports experimentally). Every element with more than one child needs display: 'flex', or Satori throws an error that says so.

Adding a logo or image

Load the file and pass it as a data URI:

// src/pages/og/[...slug].png.ts (excerpt)
const logo = await readFile('src/assets/logo.png');
const logoSrc = `data:image/png;base64,${logo.toString('base64')}`;

// inside children:
{
  type: 'img',
  props: { src: logoSrc, width: 96, height: 96 },
}

Set width and height on images. Satori needs them to lay out the frame.

Long titles

A 90-character title at 64 px will overflow. Scale the font size with the title length:

const size = post.data.title.length > 60 ? 52 : 64;

Or shorten very long titles in the endpoint before rendering, and keep the full title in the page itself.

Build time and caching

Each image takes some time to render. For tens or a few hundred posts this is negligible next to the rest of the build. For thousands, two options help:

  1. Cache by content. Write generated images to a cache folder keyed by a hash of title and date, and skip unchanged ones. This takes a small amount of custom code around the endpoint.
  2. Use your host’s build cache. If the host restores node_modules/.astro and your cache folder between builds, unchanged images aren’t regenerated. The CI build cache tip shows how to persist folders on common hosts.

Astro 7.4’s astro build --timings flag prints where build time goes, which tells you whether image generation is actually the slow step before you optimize it.

Other approaches

Approach Good for Trade-off
Satori at build time (this guide) Static sites, any host Adds build time; text layout limited to Satori’s CSS
One static image per post in public/ Hand-designed images Manual work per post
Runtime generation (for example @vercel/og on Vercel) Huge sites, user-generated pages Needs a server function; host-specific
Hosted image APIs No code External dependency, often paid

For a typical blog or marketing site, build-time Satori is the best balance: no runtime, no external service, and the image can’t fall out of sync with the title.

Testing the result

  1. Open dist/og/<id>.png directly to check layout and text wrapping.
  2. Deploy and run the URL through LinkedIn’s Post Inspector or the Facebook Sharing Debugger, which also clear their cached previews.
  3. Check the image size stays reasonable; a flat-color layout renders to a small PNG, while photographic backgrounds grow quickly.

This fits into the wider Astro SEO checklist, next to sitemaps and structured data. If you’re starting a blog and want a finished design to generate images for, the Astro blog and editorial themes include post layouts you can extend. The Astro config docs cover the site option these URLs depend on, and the Satori README lists every supported CSS property. Astro’s own endpoints documentation explains static endpoints in general.

FAQ

What size should an Astro OG image be?

Use 1200 x 630 pixels. It’s the size Facebook and LinkedIn recommend for large link previews, and X crops it cleanly for summary_large_image cards.

Can Satori use WOFF2 fonts?

No. Satori accepts TTF, OTF and WOFF font data. If you only have WOFF2, convert it or use the WOFF files that Fontsource packages include.

Why does Satori say an element needs display flex?

Satori requires display: 'flex' on any element with more than one child, because flexbox is its main layout model. Add it to the parent element named in the error.

Do generated OG images work on a static Astro site?

Yes. A static endpoint with getStaticPaths() runs during astro build and writes each PNG to dist/, so any static host serves them as normal files.

Can I use Tailwind classes in Satori?

Partly. Satori has experimental support for a tw prop that accepts Tailwind class names, but it doesn’t read your Tailwind config or stylesheets. Inline style objects are more predictable.