The HTML head is the contents of the <head>
element of an HTML document.
This part of the document is not visible to the user but is used by web browsers and search engines to know how to display the page, load external resources like CSS or scripts, or to know various information about the page.
Prerequisites
You will need to have an existing Starlight website.
Configure the HTML head in Starlight
Starlight has built-in support for customizing the HTML head of pages using a HeadConfig
object representing each element to add to the HTML head.
To add a custom element to the HTML head of every page, use the global head
configuration option in your astro.config.mjs
file:
Pages can also define custom elements to add to the HTML head for that specific page using the head
frontmatter field:
Using one of these two methods, the following HTML head is generated for the page(s):
To quickly convert head elements from HTML to the HeadConfig
format that Starlight uses (either in JavaScript or YAML), you can use the Starlight <head>
Generator which is a small web application that I made to help with this task.
Custom HTML head examples
The following examples illustrate various use cases for customizing the HTML head of Starlight pages.
Open Graph images
Open Graph Data can be used by social media platforms like Facebook, X (formerly called Twitter), or Discord to add an image to your Starlight page links when sharing them.
The image URL can be defined using the og:image
and twitter:image
meta tags:
Web analytics
To start using most web analytics tools like Plausible, Fathom, or Cloudflare Web Analytics, you usually need to add a script to the HTML head of your pages:
Google Tag Manager
Setting up Google Tag Manager in Starlight involves a slightly different approach than the previous examples as it requires adding a <script>
tag to the HTML head but also a <noscript>
tag to the HTML body.
Starlight component overrides can be used to add the <noscript>
immediately after the <body>
tag as recommended by Google.
The <SkipLink/>
component is a good candidate for this as it is already rendered at the top of the HTML body.
Create a custom Astro component to replace the existing <SkipLink/>
built-in component:
Configure Starlight to use this new component instead of the built-in one by specifying its path in the components
configuration option and also add the <script>
tag to the HTML head:
Google Fonts
Some libraries simplify using Google Fonts like Fontsource which provides various other benefits like self-hosting performance improvements, versioning, privacy, and more. The Starlight documentation contains a guide on how to use Fontsource with Starlight, but if you want to use Google Fonts directly, you can use the following configuration to load the font:
Load a JavaScript file
To load a JavaScript file that should not be processed by Astro, you can place it in the public/
directory and use the following configuration to load it: