Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Technology

How to Auto-Generate Open Graph Images in Astro with Satori and Sharp (2026 Guide)

Generate branded Open Graph images automatically in Astro with Satori and Sharp, connect social metadata, and test previews before publishing.

By Duong Hoang Nam
How to Auto-Generate Open Graph Images in Astro with Satori and Sharp (2026 Guide)

Open Graph images determine how your articles appear when somebody pastes a link into a social network, messaging app, or team chat. You can publish a technically excellent Astro tutorial and still end up with a generic, outdated, or missing link preview.

For a growing blog, manually exporting a separate social card for every article also becomes tedious. A title changes, the card becomes outdated. An editor adds a new article, somebody forgets to create the image. An older URL is shared and points to a missing graphic.

A better approach is to generate social preview images automatically from validated article metadata at build time. In this guide, we’ll use Astro static endpoints, Satori, and Sharp to turn each published article’s title and category into a branded PNG social card. We’ll then connect that image to the page’s Open Graph and X/Twitter metadata.

The example is designed for a static Astro blog with Markdown articles, a content collection, and a Git-based CMS such as Decap CMS. It is a reference implementation, not a claim that this code is already running on DuongHoangNam.com.

1. What Are Open Graph Images?

Open Graph (OG) metadata is information inside the HTML <head> that gives compatible services a title, description, canonical URL, and image for a shared page.

A simple example:

<meta property="og:title" content="A Practical Guide to Astro" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://example.com/blog/astro-guide/" />
<meta property="og:image" content="https://example.com/og/astro-guide.png" />

The og:image points to an actual publicly accessible image file. It is not the same thing as the visible featured image inside your article, although both can use the same source if you prefer.

A practical default for wide social cards is 1200 × 630 pixels (approximately 1.91:1). This is a useful design target, not a guarantee that every platform will display the image without cropping.

Unlike standard article illustrations, social cards benefit from legible typography, a short headline, recognizable branding, and generous padding around important elements.

2. Architecture: From CMS Draft to Social Preview

The pipeline we’ll build is:

Decap CMS / Markdown
        |
        v
Astro Content Collection
        |
        v
Published posts only
        |
        v
Static /og/[slug].png endpoint
        |
        v
Satori: title + brand -> SVG
        |
        v
Sharp: SVG -> PNG 1200 x 630
        |
        v
Cloudflare Pages static asset
        |
        v
og:image / twitter:image tags

The key distinction is build-time generation. During astro build, Astro asks the endpoint to generate each image. When the site is deployed, the resulting PNG files are ordinary static assets. Social crawlers don’t need to execute JavaScript or wait for a server to render an image on every request.

A five-stage workflow from Decap CMS Markdown through Astro, Satori, Sharp, and a social preview card

Figure 1: A build-time pipeline creates an independent Open Graph PNG for each published article.

3. Prerequisites and Project Assumptions

You’ll need:

  • A working Astro site with npm run build.
  • A blog content collection readable with getCollection('blog').
  • Flat, URL-safe post IDs such as my-astro-guide (we explain nested IDs later).
  • Node.js available during the build.
  • A locally stored, legally licensed TTF, OTF, or supported WOFF font file.
  • Permission to edit the article layout and add a static route.

The snippets assume your collection exposes a string title, an optional category, and an optional boolean draft. The field names and file paths must be adapted to your own Decap CMS frontmatter; they are not a replacement for an existing content schema.

For a site deployed on Cloudflare Pages, build-time Node.js access is relevant because we are generating static files during the build, not executing Node’s filesystem API inside a Cloudflare Worker at request time.

4. Install Satori and Sharp

From your Astro project directory:

npm install satori sharp

Satori renders a constrained HTML/CSS-like tree into SVG. Sharp converts the SVG into a PNG buffer.

The core conversion is straightforward:

const svg = await satori(tree, options);
const png = await sharp(Buffer.from(svg)).png().toBuffer();

Satori requires font data when rendering text. Its supported layout and CSS features are not identical to a full browser engine, so keep social-card designs simple and test real output.

Choose a font that includes every character your articles may use. For an English/Vietnamese blog, verify that the chosen font includes Vietnamese diacritics before publication. Download the font from its official provider under a suitable license; do not copy unrelated font files into a public repository without checking redistribution rights.

For this example, place a permitted font at:

src/assets/fonts/Inter-Bold.ttf

The font path is a local project prerequisite. The companion package intentionally does not contain or redistribute a font file.

5. Create a Reusable OG Image Renderer

Create src/lib/og-image.ts:

import { readFile } from 'node:fs/promises';
import satori from 'satori';
import sharp from 'sharp';

const font = await readFile(
  new URL('../assets/fonts/Inter-Bold.ttf', import.meta.url)
);

export interface OgImageOptions {
  title: string;
  category?: string;
}

export async function createOgImage({
  title,
  category = 'Tutorials',
}: OgImageOptions): Promise<Buffer> {
  const displayTitle = title.length > 100
    ? `${title.slice(0, 97).trimEnd()}…`
    : title;

  const tree = {
    type: 'div',
    props: {
      style: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        width: '100%',
        height: '100%',
        backgroundColor: '#06172D',
        color: '#FFFFFF',
        padding: '66px 72px',
        fontFamily: 'Inter',
      },
      children: [
        {
          type: 'div',
          props: {
            style: { color: '#48D9F2', fontSize: 30 },
            children: 'DuongHoangNam.com',
          },
        },
        {
          type: 'div',
          props: {
            style: {
              display: 'flex',
              flexDirection: 'column',
              gap: 22,
            },
            children: [
              {
                type: 'div',
                props: {
                  style: { color: '#B3A1FF', fontSize: 27 },
                  children: category,
                },
              },
              {
                type: 'div',
                props: {
                  style: {
                    fontSize: 58,
                    lineHeight: 1.12,
                    maxWidth: 1020,
                  },
                  children: displayTitle,
                },
              },
            ],
          },
        },
        {
          type: 'div',
          props: {
            style: { color: '#C6D7E8', fontSize: 23 },
            children: 'AI Tools  •  Automation  •  Software Engineering',
          },
        },
      ],
    },
  };

  const svg = await satori(tree as any, {
    width: 1200,
    height: 630,
    fonts: [{
      name: 'Inter',
      data: font,
      weight: 700,
      style: 'normal',
    }],
  });

  return sharp(Buffer.from(svg))
    .png({ compressionLevel: 9 })
    .toBuffer();
}

This renderer uses a plain object tree instead of JSX, so you don’t need to add a React renderer to Astro. The as any cast is limited to the Satori input tree in this compact educational example; a larger project can use Satori’s own JSX/runtime types instead.

Long titles and brand consistency

The simple 100-character limit prevents exceptionally long titles from flooding the card, but a character limit is not a typography guarantee. Always inspect a few long titles, short titles, punctuation-heavy titles, and non-English titles. Adjust font size or line wrapping if necessary. The full article title remains in page metadata even if its visual representation is shortened.

If your existing blog has a specific brand font or color palette, reuse those values rather than introducing a second identity solely for OG cards.

6. Generate a PNG for Every Published Article

Create a static endpoint at src/pages/og/[slug].png.ts:

import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';
import { createOgImage } from '../../lib/og-image';

export const prerender = true;

export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await getCollection('blog', ({ data }) =>
    data.draft !== true
  );

  return posts.map((post) => ({
    params: { slug: post.id },
    props: {
      title: post.data.title,
      category: post.data.category ?? 'Tutorials',
    },
  }));
};

export const GET: APIRoute = async ({ props }) => {
  const png = await createOgImage({
    title: String(props.title),
    category: String(props.category),
  });

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

Given a post with id: 'my-astro-guide', Astro should generate:

/og/my-astro-guide.png

The result is a PNG, not a WebP. PNG is a conservative choice for social-card compatibility. You can continue using optimized WebP images for the article’s featured image and inline illustrations; those are separate delivery decisions.

Adapt the content schema, not the other way around

If your post identity is stored in a slug field instead of post.id, derive a safe route from the same value used for the article URL. If IDs contain nested paths such as 2026/my-astro-guide, a single [slug] route will not model them correctly; use a rest route or a deliberate flat slug mapping, and test collisions.

If your project does not use Astro’s Content Layer API or its content-collection names differ, adapt getCollection() before copying the example.

Don’t expose drafts

Filtering data.draft !== true prevents ordinary CMS drafts with draft: true from receiving a public social image. It does not automatically cover every draft workflow: Git-based editorial branches may be excluded from a production build for different reasons. Verify your actual publishing pipeline.

7. Build the Site and Inspect the Output

Run:

npm run build
npm run preview

Open an image route for a published sample article:

http://localhost:4321/og/my-astro-guide.png

Depending on preview port and configuration, the exact local URL may differ. Check the terminal output instead of assuming port 4321.

Also inspect the build output:

dist/og/my-astro-guide.png

A successful build proves that the endpoint generated files, but it does not prove the design will render well in every social platform. Open at least three generated images and check text cropping, whitespace, title truncation, Unicode glyphs, and actual file size.

If you see a missing-font error, confirm the local path and selected font format. If a heading renders as unexpected symbols, verify font coverage.

8. Attach the Generated Image to Article Metadata

The PNG file alone does not create a social preview. You must point your article’s metadata at it.

In the existing Astro article layout, derive an absolute URL from the published article ID:

const imageUrl = new URL(
  `/og/${entry.id}.png`,
  Astro.site!
).href;

const articleUrl = new URL(
  `/blog/${entry.id}/`,
  Astro.site!
).href;

The non-null assertion assumes the site property is configured in astro.config.mjs. It should be set to the actual canonical domain. Make sure the article route uses the same ID and trailing-slash convention.

A minimal metadata block can include:

<meta property="og:type" content="article" />
<meta property="og:title" content={entry.data.title} />
<meta property="og:description" content={entry.data.description} />
<meta property="og:url" content={articleUrl} />
<meta property="og:image" content={imageUrl} />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta
  property="og:image:alt"
  content={`Branded social card: ${entry.data.title}`}
/>
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={imageUrl} />

Astro renders those values into the server-generated HTML, so crawlers do not need client-side JavaScript to discover them.

Important: Do not paste a second set of og:title, og:image, or canonical tags into a layout that already generates them. Find your current SEO component, then modify its existing social-image source. Duplicate contradictory tags are harder to maintain and may lead services to select the wrong image.

9. Why Absolute URLs, Dimensions, and Alt Text Matter

Social crawlers operate outside the context of your browser’s current page. A relative path such as /og/post.png is not the safest value for og:image. Use a public absolute HTTPS URL and verify the response returns an image.

The Open Graph protocol defines structured properties for image width, height, MIME type, and alternative text. These fields let consumers understand your image without relying exclusively on inference.

How an Astro layout connects og:image, twitter:card, image dimensions, and alt text to a social preview card

Figure 2: Generate absolute, publicly reachable image metadata from the same article record.

For image accessibility, describe the graphic’s useful content in og:image:alt rather than repeating a keyword list. For an image consisting mostly of a title, naming the title and brand can be appropriate.

10. Configure Astro’s Canonical Site URL

Your Astro configuration should declare the production website URL:

import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://example.com',
});

The domain above is a placeholder. Keep your current configuration and integrations; do not overwrite an existing astro.config.mjs just to add the one setting from an example.

If the website is available on both www and apex domains, choose the canonical hostname consistently. Social metadata should use the same domain as canonical URLs. A redirect from www to apex is handled by hosting or edge routing, not simply by writing a canonical tag.

11. What Happens When the Title or Slug Changes?

A static generated card reflects the content at the time of the last successful build.

  • Title changes: rebuild the site so the PNG reflects the updated heading.
  • Slug changes: generate a new image route and update article metadata; configure an appropriate redirect for the old article URL.
  • Card changes but image path stays the same: a social platform may continue displaying an older cached image.

Cache invalidation is a separate issue from image generation. For significant card redesigns, consider versioned filenames or provider-specific rescraping tools where available. A query parameter does not guarantee every crawler will refresh its cache.

Avoid setting a year-long immutable browser cache on URLs that will be overwritten with new bytes whenever an article title changes.

You do not need to replace your editorial cover images with these generated cards.

Asset Main purpose Practical format
Featured image Visual storytelling inside the article Optimized WebP/AVIF/JPEG
Inline illustrations Explain technical concepts Optimized WebP/AVIF
Generated Open Graph image Link preview on social platforms PNG or compatible JPEG
Social metadata Tell crawlers which card to use HTML meta tags

An automatically generated social card is useful for consistency. A bespoke illustration can still work better for highly visual topics. A mature content pipeline can use a CMS-provided dedicated OG image when available and fall back to the generated card otherwise.

Measure actual image sizes rather than assuming PNG is always small. Sharp’s PNG compression is lossless and text-heavy cards can compress well, but complex illustrations may benefit from JPEG. Validate the card on the platforms you actually use.

13. Security and Operational Considerations

This example creates images from CMS-controlled text. It does not accept arbitrary internet requests to generate expensive images on demand, which keeps the runtime attack surface small.

Still, review these issues:

  • Limit extremely long titles and test unusual Unicode or bidirectional text.
  • Keep the font asset properly licensed and available during the build.
  • Exclude unpublished content from the generated routes.
  • Avoid remote images, fonts, or network requests during build unless they are necessary and reliable.
  • Use npm ci in CI where a valid lockfile exists, so the dependency tree is reproducible.
  • Monitor build time as the number of articles grows.
  • Verify that a failing image render fails the build rather than silently publishing a missing route.

If you later move to an on-demand image-generation service, reassess caching, resource limits, URL input validation, and runtime compatibility. A Node.js-based Sharp build script is not automatically portable to every Cloudflare Workers runtime.

14. Test the Actual Published Social Preview

After deployment, check both the page and its generated image URL. Open the article source and verify that all expected meta tags appear once.

Use a simple request to check the PNG:

curl -I https://example.com/og/my-astro-guide.png

Expected characteristics include an HTTP success response, Content-Type: image/png, and an accessible image body. curl -I checks headers but doesn’t validate image pixels; open the actual image in your browser too.

For Facebook, use the official Sharing Debugger at https://developers.facebook.com/tools/debug/. For other services, inspect their current preview or sharing tools. Some crawlers cache previews, so an immediate mismatch does not always mean the HTML is wrong.

A pre-publish checklist for Open Graph images including PNG availability, metadata uniqueness, social previews, and cache checks

Figure 3: Verify the file and the rendered metadata before interpreting a social preview.

15. Troubleshooting Common Problems

Symptom Likely cause Recommended action
Build fails with missing font Font file not present at the expected path Add your licensed font and check the build log
PNG URL returns 404 Endpoint not generated, excluded draft, or slug mismatch Inspect dist/og and collection IDs
Browser image works but preview is blank No og:image, blocked crawler, or outdated cache Inspect rendered HTML and provider diagnostics
Wrong card appears Duplicate OG tags or wrong image URL Consolidate metadata into one SEO component
Non-English text displays incorrectly Incomplete font glyph coverage Use a font with appropriate language support
Text is clipped Layout or title too long Reduce size, adjust wrapping, inspect output
Title updated but preview is old Platform caches the old card Rebuild, redeploy, and request a rescrape if supported
Production build passes but local test fails Differences in build environment or source data Reproduce with the project’s documented build settings

Do not attempt to solve a missing social preview by adding unrelated JSON-LD markup. Open Graph metadata and structured data serve different purposes and should both remain accurate.

16. Production Readiness Checklist

Before enabling automatic OG image generation for your whole blog:

  • Existing metadata and featured-image handling have been audited.
  • Satori and Sharp are compatible with your build environment.
  • A licensed font with suitable glyph coverage is available.
  • Published article IDs map to unique image routes.
  • Draft posts are excluded from public image generation.
  • Every card builds successfully at 1200 × 630.
  • Short, long, and multilingual titles render correctly.
  • Image paths appear in the final dist/ output.
  • The page exposes a single coherent set of OG tags.
  • og:url and the canonical page URL agree.
  • Generated image URLs are absolute and use HTTPS.
  • Social preview checks pass on the platforms you use.
  • Cache behavior after title or design changes is understood.
  • The change has been reviewed in a branch and preview deployment.

17. Frequently Asked Questions

Does an Open Graph image directly improve Google rankings?

No guaranteed direct ranking improvement follows from adding a social preview image. The primary benefit is a more recognizable shared link. Search traffic, link engagement, and social distribution depend on many factors and should be measured, not assumed.

Yes, on platforms that support it. A PNG or JPEG fallback is often a more conservative cross-platform default. The ideal choice depends on the services your readers use.

Does this require an always-running server?

No. In the static deployment shown here, the PNG files are created during the Astro build and served as files by the hosting platform.

Is Satori a screenshot tool?

No. It renders a supported subset of HTML/CSS-like elements into an SVG. It doesn’t fully emulate a browser. Use an actual browser or image viewer to inspect the final output.

Can Decap CMS editors choose a custom social card?

Yes. You can add an optional socialImage field to your CMS schema. Your article layout would use that image when supplied and otherwise fall back to /og/{slug}.png. This guide starts with the simpler automatic-only approach.

Should I add Open Graph tags inside the Markdown body?

Usually not. Put them in the shared article layout or SEO component and generate values from validated frontmatter. This avoids inconsistent metadata and duplicated code in individual posts.

18. Final Thoughts

Automated social cards are a useful addition to a publication workflow, especially when a site publishes technical tutorials regularly. Satori and Sharp make it possible to turn article titles into branded images without maintaining a separate design file for every post.

The real value comes from connecting the whole chain: CMS metadata → validated content → build-time image generation → absolute Open Graph URL → tested social preview.

Start with a few published articles, inspect the generated images, and integrate the metadata into your existing Astro layout rather than replacing working SEO components.

A consistent preview makes a link easier to recognize, but useful content still does the hard work of earning attention and trust.


Continue Reading

Official Technical References

Technical disclosure: This article presents a reference implementation designed for static builds. Its code has not been executed against the production repository, and the companion package intentionally contains no proprietary or third-party font binary. Adapt collection schemas, routes, fonts, and metadata components, then test the generated build in a separate branch before deployment.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles