Open Graph images for every Astro page, from one layout
· 3 min read
Astro sites usually share one base layout, which makes it the right place for the Open Graph image too. Add one tag there and every page gets a card built from its own title and description.
Add it to the layout
This uses the page's full address, so set site in astro.config.mjs if you haven't already.
---
// src/layouts/Base.astro
const og = new URL("https://ogsmith.app/api/og");
og.searchParams.set("key", import.meta.env.OGSMITH_KEY);
og.searchParams.set("url", new URL(Astro.url.pathname, Astro.site).href);
---
<head>
<meta property="og:image" content={og.href} />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<slot name="head" />
</head>With url, OGsmith reads the page's own og:title and og:description (or its <title> and meta description) and builds the card from them. The page is read once and cached for a day.
Or say exactly what goes on the card
If a page knows better, pass the text yourself. Anything you set wins over what the page says.
og.searchParams.set("title", Astro.props.title);
og.searchParams.set("site", "example.com");Static builds
Nothing changes for output: "static". The tag is written into the HTML at build time and the image is rendered the first time a platform asks for it, so your build doesn't get any slower.