Skip to main content

Dynamic OG images / SvelteKit

Dynamic OG images in SvelteKit

Give every page of a SvelteKit app its own social card: sign one image URL in the server load function and print the tags in svelte:head. The key never reaches the browser.

The editor is free and needs no signup. Saving a template and creating an API key take a free account.

Social card for the post "A year of runes", rendered from one template

A year of runes

?description=What+%24state+changed+for+us.&title=A+year+of+runes&s=...

Social card for the post "Form actions without JavaScript", rendered from one template

Form actions without JavaScript

?description=Progressive+enhancement%2C+measured.&title=Form+actions+without+JavaScript&s=...

Social card for the post "We deleted our API layer", rendered from one template

We deleted our API layer

?description=Load+functions+all+the+way+down.&title=We+deleted+our+API+layer&s=...

One template, three posts. Each card is a signed URL that carries the post's own title; the design never changes. Start from this design or pick another in the template gallery.

SvelteKit has no built-in way to draw an Open Graph image, so most apps either ship one static file for every page or add a Satori endpoint with its own fonts and layout code. A signed URL needs neither: the card is designed once in the editor, and the server load function builds a URL with the page's title in it. The image is rendered on betterimage.io the first time a crawler asks for it and cached at the edge after that.

You need one package and a few lines in the load function your posts already have.

How it works

Design the template once

Colors, fonts, layout and logo live in a saved template in the editor.

Sign one URL per page

Your SvelteKit code puts the page's title in the URL and signs it with your key.

Crawlers get the card

The first fetch renders the 1200x630 PNG; after that it is served from the edge cache.

  1. 1 Save a template and create an API key

    Design the card in the editor and save it as a template with a free account. The template's slug, for example blog-card, is what the code below refers to. Then create a key under Account settings > API. Keys look like bi_<key_id>_<secret>: the key id appears in every image URL, the secret only signs them and never leaves your server.

  2. 2 Declare the key and add the package

    Put the full key in .env, and in your host's environment variables for production. SvelteKit 3 reads environment variables through src/env.ts: a variable declared there without public: true can only be imported from $app/env/private, which SvelteKit refuses to bundle for the browser.

    # .env
    BETTERIMAGE_API_KEY=bi_<key_id>_<secret>
    
    npm install @betterimage/cards
    
    // src/env.ts
    import { defineEnvVars } from "@sveltejs/kit/env";
    
    export const variables = defineEnvVars({
      BETTERIMAGE_API_KEY: {
        description: "betterimage.io API key, bi_<key_id>_<secret>",
      },
    });
  3. 3 Sign the URL in the server load function

    +page.server.ts only ever runs on the server, so the secret stays there and the page receives the finished URL as data.

    // src/routes/blog/[slug]/+page.server.ts
    import { error } from "@sveltejs/kit";
    import { BETTERIMAGE_API_KEY } from "$app/env/private";
    import { parseApiKey, signedImageUrl } from "@betterimage/cards";
    import { getPost } from "#lib/posts";
    
    export async function load({ params }) {
      const post = await getPost(params.slug);
      if (!post) error(404);
    
      const ogImage = await signedImageUrl({
        ...parseApiKey(BETTERIMAGE_API_KEY),
        template: "blog-card",
        fields: { title: post.title, description: post.excerpt },
      });
    
      return { post, ogImage };
    }
  4. 4 Print the tags in svelte:head

    The width and height tell platforms the size before they download the image, which lets the large card show on the very first share.

    <!-- src/routes/blog/[slug]/+page.svelte -->
    <script lang="ts">
      let { data } = $props();
    </script>
    
    <svelte:head>
      <title>{data.post.title}</title>
      <meta property="og:image" content={data.ogImage} />
      <meta property="og:image:width" content="1200" />
      <meta property="og:image:height" content="630" />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:image" content={data.ogImage} />
    </svelte:head>
    
    <h1>{data.post.title}</h1>
  5. 5 Check what crawlers see

    Run the production build with npm run build and npm run preview, open a post and view the page source. Once it is deployed, paste a post's URL into the link preview checker: it downloads the image the way X, Facebook, LinkedIn, Slack and Discord do and shows each preview.

Check a deployed page with the link preview checker. The full signing reference, with code for Node, Python, Ruby, Go and PHP, is in the API docs.

Things to watch for

The key cannot be imported in a .svelte file

Import BETTERIMAGE_API_KEY in +page.svelte instead of +page.server.ts and the build stops with: Cannot import `$app/env/private` into code that runs in the browser, as this could leak sensitive information. Sign in +page.server.ts and pass the URL to the page as data.

A missing key fails the build

Without BETTERIMAGE_API_KEY in the environment, the build stops while analysing routes with env_invalid: BETTERIMAGE_API_KEY - Value is missing. Add the variable to your CI and hosting environment before the first deploy.

$lib is #lib in SvelteKit 3

Code copied from a SvelteKit 2 project fails with: `$lib` has been removed. Use `#lib` instead. The package.json of a new SvelteKit 3 app already maps #lib to src/lib.

Special characters are already handled

Titles like "C++ tips & tricks" are the classic way to break a signed URL. The package signs the raw text and encodes the query itself, so the title arrives on the card exactly as written.

Frequently asked questions

Does this work on SvelteKit 2?

Yes. Skip src/env.ts, import the key with import { BETTERIMAGE_API_KEY } from "$env/static/private", and keep $lib instead of #lib. Everything else, the load function and svelte:head, is the same code.

Do I need Satori or an endpoint that draws the image?

No. The image is rendered by betterimage.io from a template you designed in the editor, so there are no fonts to load and no layout code in your app. Your app only builds the URL.

Does every page view cost a render?

No. A URL is rendered the first time something fetches it and then cached at the edge for a day, and cached fetches do not count against your quota. A new title makes a new URL, which renders once.

Can I use a different picture for every post?

Yes. Add image_url to fields with the post's cover photo. It is fetched server-side and drawn in the image slot of your template, keeping the template's crop framing.

What happens if the quota runs out?

The URL keeps answering with an image and a 200: the last card rendered for it, or a plain betterimage.io card for a URL never rendered before. Link previews keep working.

More guides

Give every page its own card

Design the template in the editor, save it, and the code above does the rest. Without a plan the cards carry a small watermark; an API plan removes it.