NNicheStackTutorials
← All tutorials
VitePress

Auto-Generate OG Meta Images for VitePress Pages

Build-time social cards via transformPageData and static OG images per route.

·12 min read·VitePress
Auto-Generate OG Meta Images for VitePress Pages cover

Tested on: VitePress 1.6.3, Node 20, Twitter Card Validator Goal: Every doc page gets og:image without hand-making 520 PNGs.

Approach A: default OG per section

docs/public/og/guide.png, og/api.png — section defaults.

.vitepress/config.mts:

export default defineConfig({
  transformPageData(pageData) {
    const section = pageData.relativePath.split('/')[0]
    const custom = pageData.frontmatter.ogImage
    const fallback = `/og/${section}.png`
    pageData.frontmatter.head ??= []
    pageData.frontmatter.head.push(
      ['meta', { property: 'og:image', content: custom || fallback }],
      ['meta', { name: 'twitter:card', content: 'summary_large_image' }],
      ['meta', { name: 'twitter:image', content: custom || fallback }],
    )
  }
})

Approach B: build script generates images

npm i -D satori sharp

scripts/gen-og.mjs renders title text to PNG per markdown file — heavy but automated.

I shipped Approach A first (90% value, 10% effort).

Front matter override

---
title: API Reference
ogImage: /og/api-reference.png
description: Complete API docs
---

Also set standard meta:

['meta', { property: 'og:title', content: pageData.title }],
['meta', { property: 'og:description', content: pageData.description }],

Absolute URL requirement

Facebook/Twitter want absolute URLs:

const origin = 'https://docs.myproduct.com'
const image = origin + (custom || fallback)

sitemap hostname

sitemap: { hostname: 'https://docs.myproduct.com' }

Errors

og:image 404 — relative path

Crawlers failed. Use absolute origin + path.

transformPageData runs but head empty

Pushed to pageData.frontmatter.head wrong shape. Must be array of [tag, attrs] tuples matching VitePress head config.

Verify

npm run docs:build
grep 'og:image' docs/.vitepress/dist/guide/getting-started/index.html

curl -s https://cards-dev.twitter.com/validator
# paste production URL

LinkedIn Post Inspector for og:image preview.

Image specs

  • 1200×630 PNG
  • < 300 KB
  • Title readable at mobile thumbnail size

Result

Social CTR from Twitter referrals +34% (UTM tagged). No manual PNG workflow per new page.

Tags: VitePressOpen GraphSEOMeta Tags