Dynamic OG Images in SvelteKit
SvelteKit renders pages on the server by default, so Open Graph tags you put in <svelte:head> end up in the HTML that crawlers read. That covers the tags. For the image itself, SvelteKit doesn't ship a generator. The usual DIY approach is a +server endpoint that renders a PNG with Satori.
This guide covers both parts, prerendering versus on-demand rendering, the trade-offs, and the hosted alternative: one Unfurlkit URL in your meta tag.
Sources checked (Oct 2026): SvelteKit docs for Routing (
+page,+page.server,+server) (https://svelte.dev/docs/kit/routing) and Page options (prerender,entries) (https://svelte.dev/docs/kit/page-options). Satori font formats are cross-checked against the Next.jsImageResponsedocs.
Step 1: Load data and add tags
A +page.server.js load function runs only on the server, which suits a database or a private API. Return what the page needs:
// src/routes/blog/[slug]/+page.server.js
import { error } from '@sveltejs/kit';
import { getPost } from '$lib/server/posts';
/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
const post = await getPost(params.slug);
if (!post) error(404, 'Not found');
return { post };
}
Then output the tags in the page with <svelte:head>. SvelteKit's PageProps type (2.16+) types the data prop:
Replace your-site.com with your own site.
<!-- src/routes/blog/[slug]/+page.svelte -->
<script lang="ts">
import { page } from '$app/state';
import type { PageProps } from './$types';
let { data }: PageProps = $props();
const origin = 'https://your-site.com'; // your production origin
const ogImage = `${origin}/og/${data.post.slug}.png`;
</script>
<svelte:head>
<title>{data.post.title}</title>
<meta property="og:title" content={data.post.title} />
<meta property="og:description" content={data.post.description} />
<meta property="og:type" content="article" />
<meta property="og:url" content={`${origin}${page.url.pathname}`} />
<meta property="og:image" content={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={ogImage} />
</svelte:head>
<h1>{data.post.title}</h1>
Use a fixed production origin (from config or an env var) rather than the request host. Behind proxies or on preview deployments, the request host might not be the URL people share.
Don't turn off SSR for these pages. export const ssr = false makes the page render only in the browser. Crawlers generally don't run JavaScript, so they won't see tags added that way.
Step 2 (DIY): A +server endpoint that renders the PNG
A +server.js file exports handlers named after HTTP methods (GET, POST, and so on) that receive a RequestEvent and return a Response. Per the routing docs, +layout files don't apply to +server files.
npm install satori @resvg/resvg-js
// src/routes/og/[slug].png/+server.js
import { error } from '@sveltejs/kit';
import satori from 'satori';
import { Resvg } from '@resvg/resvg-js';
import { getPost } from '$lib/server/posts';
import fontData from '$lib/fonts/Inter-Bold.ttf?arraybuffer'; // see note below
/** @type {import('./$types').RequestHandler} */
export async function GET({ params }) {
const post = await getPost(params.slug);
if (!post) error(404, 'Not found');
const svg = await satori(
{
type: 'div',
props: {
style: {
width: '100%', height: '100%', display: 'flex',
flexDirection: 'column', justifyContent: 'center',
padding: 72, background: '#0b0d12', color: '#fff',
fontFamily: 'Inter', fontSize: 64,
},
children: post.title,
},
},
{ width: 1200, height: 630, fonts: [{ name: 'Inter', data: fontData, weight: 700, style: 'normal' }] }
);
const png = new Resvg(svg).render().asPng();
return new Response(png, {
headers: {
'Content-Type': 'image/png',
'Cache-Control': 'public, max-age=86400',
},
});
}
Loading the font. Satori needs the font as binary data, in TTF, OTF, or WOFF (not WOFF2). How you load it depends on your adapter. Reading from disk with node:fs works on Node-based adapters. On edge runtimes, import or fetch it instead. The ?arraybuffer import above is a placeholder for whatever your bundler setup supports.
Prerender or render on demand?
SvelteKit's prerender page option also applies to +server files. You have two choices:
Prerender at build time (works with adapter-static):
// src/routes/og/[slug].png/+server.js
export const prerender = true;
/** @type {import('./$types').EntryGenerator} */
export async function entries() {
const posts = await getAllPosts();
return posts.map((p) => ({ slug: p.slug }));
}
You need entries(). The prerenderer discovers pages by following <a> links, and nothing links to your OG images with an <a> tag. They only appear in <meta> tags. Without entries (or config.prerender.entries), the images won't be generated.
Render on demand (needs a server adapter): leave prerender off and rely on Cache-Control and your host's CDN so each image is rendered once rather than on every crawl.
The honest trade-offs
- Prerendered: build time grows with posts, and
@resvg/resvg-jsis a native dependency that can be awkward in some CI images. - On demand: you pay compute per uncached request, you need sensible cache headers, and you should rate-limit or validate inputs so the endpoint can't be used to render arbitrary text.
- Runtime differences: native Resvg doesn't run on edge runtimes, so you'd need the WASM build there, and font loading differs per adapter.
- Satori's CSS subset: flexbox, not grid. Multi-child elements need
display: flex. - The design lives in code, and changes need a deploy.
None of these block you. They're ongoing maintenance.
Step 2 (alternative): One URL with Unfurlkit
Delete the og/ route and change one line in the page:
<script lang="ts">
import type { PageProps } from './$types';
let { data }: PageProps = $props();
const ogImage =
'https://unfurlkit.com/v1/basic.png?' +
new URLSearchParams({ title: data.post.title || 'My Blog', theme: 'dark' }).toString();
</script>
The <svelte:head> block from Step 1 stays the same. You can remove satori, @resvg/resvg-js, and the font file.
The basic template accepts title (trimmed to 120 characters), subtitle (160), theme (dark or light), and accent (6-digit hex without #). Unknown parameters return 400.
Signing for Pro. Every image URL needs your key. A Free key gets 10 renders in total (no monthly reset), with a small "unfurlkit" watermark, and needs no card. Pro is $9/mo or $90/yr, with 10,000 renders a month, no watermark, and custom fonts (Inter, Roboto, Playfair Display, JetBrains Mono) and logo. Pro URLs need your public key k and an HMAC signature s made with your secret key. In SvelteKit, build the signed URL in +page.server.js (server-only, where $env/static/private is available) and return it in data. Never sign in +page.svelte or a universal +page.js, because those also run in the browser. See Signing Pro URLs for the Node and Python snippets.
// src/routes/blog/[slug]/+page.server.js (sketch)
import { UNFURLKIT_SECRET_KEY } from '$env/static/private';
import { signOgUrl } from '$lib/server/unfurlkit'; // the Node snippet from signing-pro-urls.md
export async function load({ params }) {
const post = await getPost(params.slug);
return { post, ogImage: signOgUrl({ title: post.title, theme: 'dark' }, UNFURLKIT_SECRET_KEY) };
}
A render is counted only when a unique image is generated and wasn't already cached. Shares and cache hits don't count. Over the limit, images keep rendering. On a signed Free key, images already made keep showing, and new ones get a plain version (your title on the basic card, with the small mark) that doesn't count. Upgrade to Pro for more renders. Upgrade to Pro to remove watermarks from all your images.
What changes:
- Works the same on every adapter, including static, Node, serverless, and edge, because nothing renders in your app.
- No
entries()bookkeeping for prerendering images. - No native dependencies in CI.
- Absolute 1200×630 PNG URLs by default.
Which option should you use?
| Situation | Use |
|---|---|
| Static site, a handful of posts, like owning the code | Prerendered +server + entries() |
| Server adapter, comfortable with caching and rate limits | On-demand +server |
| Mixed adapters, edge runtime, or no wish to maintain rendering | Unfurlkit URL |
Debugging checklist
- View source (not DevTools) of the live page. Are the
og:tags in the server HTML? If not, check thatssrisn'tfalsefor the route. - Is
og:imageabsolute and on your production origin? - DIY prerender: does
build/og/<slug>.pngexist? If not, addentries(). - Open the image URL. It should return 200 with
image/png. On demand, check your function logs for font-loading errors. With Unfurlkit, a400means a missing title or an invalid parameter. A bad signature doesn't error: the image renders with the watermark and anX-Unfurlkit-Signatureheader. - Size limits. Meta documents 8 MB maximum, LinkedIn 5 MB, and WhatsApp recommends under 600 KB. See the OG image size guide.
- Refresh caches with Meta's Sharing Debugger (https://developers.facebook.com/tools/debug/) and LinkedIn's Post Inspector (https://www.linkedin.com/post-inspector/).
- Run the page through the Free OG Image Checker for previews on X, LinkedIn, Facebook, WhatsApp, Slack, Discord, and iMessage. We don't store the URLs you check.
FAQ
Which languages and scripts are supported? Right-to-left scripts such as Arabic and Hebrew aren't supported yet at launch.
Can I put the tags in +layout.svelte?
Yes, for site-wide defaults. Pages that set the same tags in their own <svelte:head> will add a second tag, so either set per-page values only, or pass values from the page up to the layout through data.
Does SvelteKit dedupe <svelte:head> tags?
Don't rely on it. Check the rendered HTML for duplicate og:image tags.
Svelte 4 syntax?
The examples use Svelte 5 runes ($props()). In Svelte 4 you'd write export let data, as the SvelteKit docs note.
Summary
SvelteKit's server rendering makes the tags straightforward with <svelte:head>. Generating the image means a +server endpoint plus decisions about prerendering, fonts, runtimes and caching. If you don't want to make those decisions, one Unfurlkit URL replaces the route.
See Unfurlkit pricing · Check any page with the Free OG Image Checker.