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 the required packages:

    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,
    bgImage: {
    path: "./src/pages/og/_background-image.png",
    },
    };
    },
    });
  3. Modify the <Head/> component:

    src/components/Head.astro
    ---
    import Default from "@astrojs/starlight/components/Head.astro";
    const ogImageUrl = new URL(
    `/astro-supernova/og/${Astro.locals.starlightRoute.id.replace(/\.\w+$/, ".png")}`,
    Astro.site,
    );
    ---
    <Default><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