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.
Starlight does not yet provide a built-in mechanism to automatically generate these images using all the available page data and add the corresponding meta tags to your pages.
This guide will show one possible way to do so using astro-og-canvas
which uses an Astro endpoint to generate the images.
The generated images can be customized using a large set of options including size, colors, fonts, logos, and more.
Prerequisites
You will need to have an existing Starlight website.
Install astro-og-canvas
Start by installing the astro-og-canvas
package:
Create the image endpoint
astro-og-canvas
provides an OGImageRoute
helper that can be used to create an endpoint that will generate the various images for all documentation pages.
To do so, we need to do the following:
- Get a list of all documentation entries from the
docs
content collection used by Starlight. - Map the entry array to an object with the page ID as key and the frontmatter data as value.
- Pass down the object to the
OGImageRoute
helper. - Define a
param
option to match the name of the parameter used in the endpoint path. - Define a
getImageOptions
function called for each page to customize the generated image.
The following example will create the endpoint in a src/pages/og/[...slug].ts
file:
Visiting the endpoint will now generate an image for the page matching the slug
parameter.
For example, visiting /og/getting-started.png
would generate an image for the getting-started
page.
Override the <Head/>
component
The next step is to override the <Head/>
component used by Starlight to add the og:image
and twitter:image
meta tags containing the URL of the generated image for all documentation pages.
Create a custom Astro component to replace the existing <Head/>
built-in component:
Configure Starlight
The last step is to configure Starlight to use the custom <Head/>
component instead of the built-in one and define the site
Astro option.
The site
option contains the deploy URL of your documentation website as Open Graph images require a valid URL having the http
or https
scheme.
The following example will configure Starlight in the astro.config.mjs
file:
Preview the generated images
Using opengraph.xyz, you can preview the generated images for your documentation pages.
For example, given the following src/content/docs/getting-started.md
file accessible at https://example.com/getting-started
:
The following meta tags will be added to the page:
And the following Open Graph image will be generated:
Up to you to customize the image using the various options provided by astro-og-canvas
.
You can find the complete source code of this guide in this StackBlitz example.