Add OG Images
2 min read
This guide will show one possible way to add OG images to Starlight.
Step-by-step Guide
Section titled “Step-by-step Guide”-
Start by installing the required packages:
Terminal window npm add astro-og-canvas canvaskit-wasmTerminal window pnpm add astro-og-canvas canvaskit-wasmTerminal window yarn add astro-og-canvas canvaskit-wasmTerminal window bun add astro-og-canvas canvaskit-wasm -
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",},};},}); -
Customize
headroute 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 },})}) -
Configure Starlight in the
astro.config.mjsfile: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.