SvelteKit Integration Guide

How to configure dynamic Open Graph images in SvelteKit using svelte:head.

In SvelteKit, dynamic HTML head elements are declared directly inside the template using the native <svelte:head> element.


Route Implementation (src/routes/blog/[slug]/+page.svelte)

<script lang="ts">
  import type { PageData } from './$types';

  export let data: PageData;

  const { title, description } = data;

  $: ogParams = new URLSearchParams({
    title,
    description,
    theme: "dark",
    size: "landscape",
  });

  $: ogImageUrl = `https://api.generativeog.in/v1/images/article.png?${ogParams.toString()}`;
</script>

<svelte:head>
  <title>{title}</title>
  <meta name="description" content={description} />

  <!-- Open Graph -->
  <meta property="og:title" content={title} />
  <meta property="og:description" content={description} />
  <meta property="og:image" content={ogImageUrl} />
  <meta property="og:image:width" content="1200" />
  <meta property="og:image:height" content="630" />

  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:title" content={title} />
  <meta name="twitter:description" content={description} />
  <meta name="twitter:image" content={ogImageUrl} />
</svelte:head>

<main>
  <h1>{title}</h1>
  <p>{description}</p>
</main>

Prerendering in SvelteKit

If your route exports export const prerender = true;, SvelteKit pre-renders static HTML pages at build time. The <meta> tags with your computed image URLs are baked into the static HTML files, ensuring instant delivery to social platform bots.