Skip to content

Add OG Images to Starlight

1 min read

This guide will show one possible way to add OG images to Starlight.

  1. Start by installing all packages that need:

    Terminal window
    npm add astro-og-canvas canvaskit-wasm
  2. Create the image endpoint with this code:

    src/pages/og/[...route].ts
    import { getCollection } from 'astro:content'
    import { OGImageRoute } from 'astro-og-canvas'
    const entries = await getCollection('docs')
    const pages = Object.fromEntries(
    entries.map(({ data, id }) => [id, { data }]),
    )
    export const { getStaticPaths, GET } = OGImageRoute({
    pages,
    param: 'route',
    getImageOptions: (_path, page: (typeof pages)[number]) => {
    return {
    title: page.data.title,
    description: page.data.description,
    border: { width: 32, side: 'inline-start' },
    padding: 80,
    bgGradient: [[24, 24, 27]],
    }
    },
    })
  3. Override the <Head/> component:

    src/components/Head.astro
    ---
    import type { Props } from '@astrojs/starlight/props'
    import Default from '@astrojs/starlight/components/Head.astro'
    const ogImageUrl = new URL(
    `/og/${Astro.props.id.replace(/\.\w+$/, '.png')}`,
    Astro.site,
    )
    ---
    <Default {...Astro.props}><slot /></Default>
    <meta property="og:image" content={ogImageUrl} />
    <meta name="twitter:image" content={ogImageUrl} />
  4. Configure Starlight in the astro.config.mjs file:

    astro.config.mjs
    // ...
    export default defineConfig({
    integrations: [
    starlight({
    components: {
    Head: './src/components/Head.astro',
    },
    }),
    ],
    })

Up to you to customize the image using the various options provided by astro-og-canvas.

  1. Add Open Graph images to Starlight