Skip to content

Add OG Images

2 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. Customize head route data:

    src/routeData.ts
    ---
    import { defineRouteMiddleware } from "@astrojs/starlight/route-data"
    export const onRequest = defineRouteMiddleware((context) => {
    // Get the URL of the generated image for the current page using its ID and
    // append the `.png` file extension.
    const ogImageUrl = new URL(
    `/og/${context.locals.starlightRoute.id || "index"}.png`,
    context.site,
    )
    // Get the array of all tags to include in the `<head>` of the current page.
    const { head } = context.locals.starlightRoute
    // Add the `<meta/>` tags for the Open Graph images.
    head.push({
    tag: "meta",
    attrs: { property: "og:image", content: ogImageUrl.href },
    })
    head.push({
    tag: "meta",
    attrs: { name: "twitter:image", content: ogImageUrl.href },
    })
    })
  4. Configure Starlight in the astro.config.mjs file:

    astro.config.mjs
    export default defineConfig({
    integrations: [
    starlight({
    routeMiddleware: "./src/routeData.ts",
    }),
    ],
    });

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

  1. Add Open Graph images to Starlight - HiDeoo