Skip to content
Menu

Simplifying the <head> with astro-helmet

Updated30 November 2026
Published30 June 2024
Astronaut's helmet with code reflected off the visor.

The cover at the top of this note has two jobs. When someone shares a link, I want a crawler to find a 1200 × 630 crop of the helmet. When someone opens the page, I want their browser to fetch a cover sized for its spot on the page and the display’s pixel density. The first job needs an Open Graph image. The second can use a responsive preload. Both tags belong in the layout’s <head>, but only the page knows which image to use.

I started with a named Astro slot for page-specific tags. A slot still works well for a one-off tag. I built astro-helmet so a layout could supply a default sharing card and a note could replace it with a photo and its own alt text. The component takes ordinary data and renders HTML during the build or server render. It ships no client-side JavaScript of its own.

Give the layout defaults and the page the final say

The examples use astro-helmet 2.0, which supports Astro 4–7. If you used an earlier version, the main change to watch here is that a page’s social images replace the layout’s entire list. Upgrading to 2.0

Terminal window
npm install astro-helmet@2

Set site to your public origin in astro.config.mjs, for example defineConfig({ site: 'https://example.com' }). Put the default sharing card at public/site-card.png and the cropped photo at public/helmet-card.jpg. For the responsive example, use the original photo at src/assets/visor.jpg, at least 1440 pixels wide.

In src/layouts/Layout.astro, let the layout use the incoming title when it generates the default social tags. The browser title and og:title are separate fields. A page that only supplies { title: 'Notes' } should get “Notes” in both places.

src/layouts/Layout.astro
---
import Helmet, { createSeoHead, type HeadItems } from 'astro-helmet'
interface Props {
headItems: HeadItems
}
const { headItems } = Astro.props
const defaults = createSeoHead({
title: headItems.title || 'Field notes',
site: Astro.site,
openGraph: {
image: { url: '/site-card.png', alt: 'Field notes' }
}
})
---
<!doctype html>
<html lang="en">
<Helmet headItems={[defaults, headItems]} />
<body>
<slot />
</body>
</html>

Helmet renders the <head> wrapper, charset and viewport. If your layout already has a <head> for other Astro components, put Helmet first inside it and pass options={{ omitHeadTags: true }}. This site does that so its layout can also render Astro’s client router.

Here’s a page with its own preview image at public/helmet-card.jpg. The helper normally uses the formatted title for sharing. Setting openGraph.title keeps the short headline on the card and “Field notes” in the browser tab. To generate Twitter/X tags too, pass twitter: { card: 'summary_large_image', image: '/helmet-card.jpg' }.

src/pages/notes/helmet.astro
---
import { createSeoHead } from 'astro-helmet'
import Layout from '../../layouts/Layout.astro'
const headItems = createSeoHead({
title: 'Inside the helmet',
titleTemplate: '%s | Field notes',
description: 'A closer look at the reflections in the visor.',
site: Astro.site,
path: '/notes/helmet',
openGraph: {
type: 'article',
title: 'Inside the helmet',
image: {
url: '/helmet-card.jpg',
alt: 'Lines of code reflected in an astronaut’s visor',
width: 1200,
height: 630
}
},
jsonLd: { '@type': 'BlogPosting', headline: 'Inside the helmet' }
})
---
<Layout {headItems}>
<h1>Inside the helmet</h1>
</Layout>

With the example origin, the HTML contains one canonical link to https://example.com/notes/helmet, one og:image pointing to https://example.com/helmet-card.jpg, and a separate JSON-LD script. Choose path from the public route for the article. With Astro’s build.format: 'file', Astro.url.pathname can be /notes/helmet.html during prerendering even when the host serves /notes/helmet. Use the URL that visitors reach without a redirect, including your host’s trailing-slash convention. Inspect the built HTML to catch a filename that slipped into a canonical. Astro’s build format and URL behavior

Let the page replace the layout image

In 2.0, a page that supplies images owns the whole ordered list. Open Graph gives the first image preference and associates structured properties such as alt text and width with the og:image that precedes them. Here the visor photo gets its own description. “Field notes” belongs to the old card. Open Graph arrays and structured properties

Page input to openGraph.image Result
Omitted, [], or only blank URLs Keep the layout’s images and their fields.
A single photo Emit that photo with the fields supplied by the page.
[photo, siteCard] Emit both in that order. Include the fields you want for each.

When you list a URL again, supply the fields you want to keep for that image. For finer control, you can give a single image in a raw meta list an explicit key and replace just that image. The reference shows how to key the layout and page entries. Open Graph image overrides

Preload the image the reader will see

Back to the helmet in the article body. The notes route on this site builds a social crop and a separate responsive cover with Astro’s getImage(). The preload describes only the displayed cover. My notes use density descriptors and include the fallback src as an explicit 1x candidate in the preload’s imagesrcset and the image’s srcset.

Here’s the width-descriptor version as a standalone page. The cover takes the full viewport up to 720 CSS pixels. The browser uses that size, its pixel density and the available sources to choose a file. To use this in the article above, bring over the image imports, the getImage() call, srcset and sizes. Pass the preload in the article’s createSeoHead() options under link and render the matching <img> in its body.

src/pages/cover.astro
---
import { getImage } from 'astro:assets'
import { preloadImage } from 'astro-helmet'
import cover from '../assets/visor.jpg'
import Layout from '../layouts/Layout.astro'
const image = await getImage({
src: cover,
widths: [480, 960, 1440],
format: 'webp',
loading: 'eager',
fetchpriority: 'high'
})
const srcset = image.srcSet.attribute
const sizes = '(max-width: 720px) 100vw, 720px'
const headItems = {
title: 'The visor',
meta: [{ name: 'description', content: 'The full-width helmet cover.' }],
link: [
preloadImage({
imagesrcset: srcset,
imagesizes: sizes,
fetchpriority: 'high'
})
]
}
---
<Layout {headItems}>
<main>
<img
{...image.attributes}
src={image.src}
{srcset}
{sizes}
alt="Lines of code reflected in an astronaut’s visor"
/>
</main>
</Layout>
<style>
:global(body) {
margin: 0;
}
main {
max-width: 720px;
margin-inline: auto;
}
img {
display: block;
width: 100%;
height: auto;
}
</style>

To check reuse, open the Network panel, disable the cache and reload at a narrow viewport. Read document.querySelector('main img').currentSrc in the console. That URL should have one image transfer even though it appears in both the hint and the image’s candidates. Repeat at a wider viewport. Use this hint for a likely above-the-fold image and measure the result on the page. Astro image API

Check the built head

Run npm run build. With Astro’s default directory output, open dist/notes/helmet/index.html and check the result before deploying.

  1. There is one <head> and one canonical. The canonical and og:url both use the public article URL.
  2. The tab title includes “Field notes”, the social title reads “Inside the helmet”, and exactly one og:image points to https://example.com/helmet-card.jpg. The alt text describes the visor. Request the image URL too. A typo in a path to a public file can produce valid HTML and a 404 image.
  3. The application/ld+json block parses as JSON and its headline matches the article. Helmet adds the Schema.org context when you pass jsonLd.

For automated checks, validateHeadItems() returns issues with stable codes such as missing-description. A site that enables Astro’s Content Security Policy also needs to opt Helmet into registration. Static HTML and streaming responses deliver policies differently. Follow the recipe for how you serve the page and verify the policy in the built meta tag or HTTP header. CSP setup by deployment mode

For other head items, the package reference covers raw metadata, resource hints, custom priorities and the public TypeScript types. Package reference · astro-helmet on npm