Dynamic OG Images in Astro

Astro sites are often content-heavy (blogs, docs, changelogs), and every one of those pages benefits from a good social preview image. Unlike Next.js, Astro doesn't include a built-in OG image generator. The common pattern is to build one yourself with an endpoint plus Satori, the library behind @vercel/og.

This guide covers that DIY approach in full, including where it gets fiddly, and then shows the alternative: a meta tag pointing at a hosted Unfurlkit URL.

Version note: Written for Astro 5+ build-time content collections (defined in src/content.config.ts with the glob() loader), checked against the Astro docs in Oct 2026. See the Astro docs on endpoints (https://docs.astro.build/en/guides/endpoints/) and content collections, and the Satori README (https://github.com/vercel/satori).

The basics every OG image needs

  • 1200×630 px, PNG or JPEG
  • An absolute https:// URL in og:image
  • twitter:card set to summary_large_image
  • Publicly reachable, with no auth or bot blocking

In Astro, set site in astro.config.mjs so you can build absolute URLs:

Replace your-site.com with your own site.

// astro.config.mjs
import { defineConfig } from 'astro/config'
export default defineConfig({ site: 'https://your-site.com' })

Step 1: Add meta tags in your layout

---
// src/layouts/BaseLayout.astro
interface Props { title: string; description?: string; ogImage?: string }
const { title, description = '', ogImage } = Astro.props
const image = new URL(ogImage ?? '/og/default.png', Astro.site).href
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>{title}</title>
    <meta name="description" content={description} />
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    <meta property="og:type" content="article" />
    <meta property="og:url" content={new URL(Astro.url.pathname, Astro.site).href} />
    <meta property="og:image" content={image} />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:image" content={image} />
  </head>
  <body><slot /></body>
</html>

new URL(path, Astro.site) turns a relative path into an absolute one, which avoids the most common OG bug.

Step 2 (DIY): Generate images with Satori in an endpoint

Install the dependencies:

npm install satori @resvg/resvg-js

Satori turns a JSX-like object tree into SVG, and Resvg converts the SVG to PNG. Astro components aren't React, so you either install React for the JSX or write the tree as plain objects. The plain-object form is shown below because it needs no extra integration.

Fonts

Satori requires at least one font, passed in as binary data. Use TTF, OTF, or WOFF, since WOFF2 isn't supported. The Next.js ImageResponse docs, which use Satori, list the same three formats. Put a font in your project:

src/assets/fonts/Inter-Bold.ttf

The endpoint

Create a static endpoint that outputs one PNG per blog post at build time:

Replace your-site.com with your own site.

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

const fontData = await readFile('./src/assets/fonts/Inter-Bold.ttf')

export const getStaticPaths = (async () => {
  const posts = await getCollection('blog')
  return posts.map((post) => ({
    params: { slug: post.id }, // entry ids come from filenames (or a frontmatter `slug` override)
    props: { post },
  }))
}) satisfies GetStaticPaths

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: 64, background: '#0b0d12', color: 'white',
          fontFamily: 'Inter',
        },
        children: [
          { type: 'div', props: { style: { fontSize: 28, opacity: 0.7 }, children: 'your-site.com' } },
          { type: 'div', props: { style: { fontSize: 64, lineHeight: 1.1 }, children: post.data.title } },
        ],
      },
    },
    {
      width: 1200,
      height: 630,
      fonts: [{ name: 'Inter', data: fontData, weight: 700, style: 'normal' }],
    }
  )

  const png = new Resvg(svg, { fitTo: { mode: 'width', value: 1200 } }).render().asPng()

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

Wire it into the post page

---
// src/pages/blog/[...slug].astro
import { getCollection, render } from 'astro:content'
import BaseLayout from '../../layouts/BaseLayout.astro'

export async function getStaticPaths() {
  const posts = await getCollection('blog')
  return posts.map((post) => ({ params: { slug: post.id }, props: { post } }))
}
const { post } = Astro.props
const { Content } = await render(post)
---
<BaseLayout title={post.data.title} description={post.data.description}
  ogImage={`/og/${post.id}.png`}>
  <Content />
</BaseLayout>

On build, Astro writes dist/og/<slug>.png for every post.

Using @vercel/og instead

Some Astro projects use the @vercel/og package (or community wrappers such as astro-og-canvas) instead of calling Satori directly. @vercel/og bundles Satori and Resvg behind an ImageResponse API. It's convenient, but it is built for edge/serverless runtimes and its JSX is easiest to use with the React integration installed. Calling Satori directly, as above, has fewer moving parts in a static Astro build.

On-demand (SSR) instead of build time

If you use an adapter (@astrojs/node, @astrojs/vercel, and others), you can render on request instead. Add export const prerender = false to the endpoint, read the title from the URL or look up the entry, and remove getStaticPaths. In that case you need to add caching headers (for example Cache-Control: public, max-age=31536000, immutable on versioned URLs) and limit input length so the endpoint can't be abused.

The honest trade-offs of DIY

Satori in Astro works well, and many Astro sites ship this exact setup. Know what you're taking on:

  • Build time grows with content. Every post means another Satori and Resvg render on every build. That's fine for dozens of posts and becomes noticeable at thousands.
  • Native dependency. @resvg/resvg-js ships platform-specific binaries, which can cause trouble in some CI or serverless environments. The WASM build (@resvg/resvg-wasm) is the fallback.
  • CSS subset. Satori supports flexbox but not grid, and every multi-child element needs display: flex. You can't reuse your Astro components or Tailwind classes directly.
  • Fonts, emoji, and non-Latin text. You have to load each one yourself.
  • Templates live in code. Changing the design means a code change and a full rebuild.

Step 2 (alternative): One URL with Unfurlkit

Skip the endpoint, the dependencies, and the font files. Point og:image at a URL:

---
// src/pages/blog/[...slug].astro
const ogImage =
  `https://unfurlkit.com/v1/basic.png?title=${encodeURIComponent(post.data.title || 'My Site')}&theme=dark`
---
<BaseLayout title={post.data.title} description={post.data.description} ogImage={ogImage}>
  <Content />
</BaseLayout>

Because the URL is already absolute, new URL(ogImage, Astro.site) in the layout leaves it unchanged. You can delete src/pages/og/, uninstall satori and @resvg/resvg-js, and remove the font files.

What you get:

  • No build-time rendering. Builds no longer slow down as you add posts.
  • No native binaries in your CI.
  • Correct size and content type by default, with edge caching.
  • The same pattern on your Next.js app, Hugo docs, or plain HTML pages.

Every image URL needs your key. A Free key gets 10 renders in total (no monthly reset), with a small "unfurlkit" watermark, and needs no card. Pro, $9/mo or $90/yr (10k renders/month), removes it and adds custom fonts (Inter, Roboto, Playfair Display, JetBrains Mono) and logo.

Which should you use?

Situation Recommendation
Small static blog, you enjoy owning the code Satori endpoint
Hundreds+ of pages, slow builds, or CI trouble with Resvg Unfurlkit
Several sites on different stacks Unfurlkit
Just need one image for everything A static public/og/default.png

Debugging checklist

  1. Run astro build and check that dist/og/*.png exist (DIY) or that the meta tag contains the full Unfurlkit URL.
  2. View source of a built page. Is og:image absolute? If not, set site.
  3. Open the image URL directly. It should return 200 with image/png.
  4. Confirm twitter:card is summary_large_image.
  5. Platforms cache aggressively. Re-scrape with LinkedIn Post Inspector or Facebook Sharing Debugger, or change the URL (?v=2).

The free Free OG Image Checker shows how a URL renders on X, LinkedIn, Facebook, Slack, Discord, and iMessage and lists what to fix.

Summary

Astro doesn't generate OG images on its own, so you either build an endpoint with Satori and Resvg or point a meta tag at a hosted URL. The DIY route is free and flexible but adds build time, native dependencies, and template code. Unfurlkit keeps your Astro project to a single meta tag.

FAQ

Which languages and scripts are supported? Right-to-left scripts such as Arabic and Hebrew aren't supported yet at launch.

Do I need React to use Satori in Astro? No. Satori accepts plain objects shaped like React elements ({ type, props }), as in the endpoint above. Installing @astrojs/react lets you write JSX instead, which is easier to read for complex layouts, but it isn't required.

Can I use Tailwind classes in Satori? Satori has experimental support for a tw prop that accepts Tailwind-style classes. It isn't your project's Tailwind config, though, so custom theme values and plugins won't carry over automatically. Most teams write inline style objects instead.

Why does my OG image work locally but not in production? Usually it's one of three things: site isn't set, so the URL is relative or points to localhost; the image route is excluded or blocked in production (for example by a redirect rule or a bot-protection layer); or the platform cached an earlier, broken version. Check them in that order.

Should the OG image be PNG or JPEG? PNG is the safe default for text-heavy cards because it keeps edges sharp. JPEG produces smaller files for photographic backgrounds. Either works on all major platforms. Avoid SVG and WebP for og:image, because support across platforms is inconsistent.

Do I need a separate twitter:image? X falls back to og:image when twitter:image is missing, but setting both is harmless and makes your intent explicit. You do need twitter:card set to summary_large_image to get the large preview.

How do I handle pages that aren't in a content collection? Give the layout a default ogImage (a static file in public/), as in the BaseLayout above. With Unfurlkit, you can build the URL from Astro.props.title for any page, so you don't need a list of pages.

What about i18n sites? With Satori, load a font that covers each script you publish in, and pass several fonts if needed. With Unfurlkit, right-to-left scripts such as Arabic and Hebrew aren't supported yet at launch.

See Unfurlkit pricing · Check any page with the Free OG Image Checker.

Updated 2026-10-21

Try it freePricing