How to generate dynamic OG images in Next.js
In Next.js, return a signed Snapsbrew image URL from generateMetadata. The URL names a 1200x630 template and the text for each layer, and your server signs it with a secret key. The first request from a crawler renders the PNG. Later requests get the cached file. No route of your app renders images.
By Alejandro Medina, maintainer of Snapsbrew. Published . Last updated .
An og:image is the picture that Slack, LinkedIn, X, iMessage and Discord show when someone shares your link. A static image for the whole site works, but every share then looks the same. A dynamic image shows the title of the page, the author or the price, so people know what the link is before they click.
This guide adds a dynamic og:image to the App Router of Next.js with a signed URL from a Snapsbrew instance. The method also works with the Pages Router. Only the place where you set the meta tag changes.
What you need
- A Snapsbrew instance that the public internet can reach. Read Install with Docker.
- A Next.js app with the App Router.
- Node.js 20 or later on the server that runs Next.js.
How a signed URL works
A signed URL is a normal image URL with three query parameters:
| Parameter | Value |
|---|---|
template_id |
The UUID of the template. |
variants |
The layer changes, as JSON, in standard base64. |
signature |
The HMAC-SHA256 of the other parameters, made with your signed-URL key. |
Your server makes the URL. It does not call Snapsbrew. When a crawler opens the URL, the instance checks the signature, renders the template with the variants and redirects to the stored image. The next request for the same URL gets the stored image and renders nothing.
So the cost of an image is one render the first time the link is shared. Your Next.js app does no image work at all.
Step 1: Design the template
- On your instance, open
/templates/new. - Pick a starter template, or start from an empty canvas.
- Set the canvas to the
open_graphpreset. It is 1200x630 pixels. - Add a text layer with the key
title. Add a second text layer with the keysubtitle. - Publish the template.
Signed URLs render the published version of a template. If you edit the template later, publish it again. A publish changes the cache key, so the next request renders the new design.
Copy the UUID of the template from its URL.
Step 2: Get a signed-URL key
- Open Account > Developers.
- In Signed URL API keys, click Generate new key.
- Copy the key.
This key can sign image URLs only. It cannot call the REST API. You can keep two keys active at the same time, so you can change keys with no downtime.
Put the values in .env.local:
SNAPSBREW_URL=https://snapsbrew.example
SNAPSBREW_SIGNING_KEY=<signed-url-key>
SNAPSBREW_OG_TEMPLATE=<template-uuid>
Do not add the NEXT_PUBLIC_ prefix. Next.js sends variables with that prefix to the browser.
Step 3: Sign the URL on the server
Install the JavaScript SDK and the server-only package. The SDK is on GitHub, not on npm yet.
npm install github:amedina068/snapsbrew-js server-only
Make a helper that signs the URL. The server-only import stops the build if a client component imports the file.
// lib/og-image.ts
import 'server-only'
import { signedUrl } from 'snapsbrew'
export function ogImageUrl(title: string, subtitle: string) {
return signedUrl({
baseUrl: process.env.SNAPSBREW_URL!,
key: process.env.SNAPSBREW_SIGNING_KEY!,
templateId: process.env.SNAPSBREW_OG_TEMPLATE!,
variants: [
{ layer: 'title', text: title },
{ layer: 'subtitle', text: subtitle },
],
})
}
signedUrl() returns a promise, because it uses Web Crypto. The same code runs on Node.js, Bun, Deno and Cloudflare Workers.
If you do not want a dependency, sign the URL with node:crypto. The rules are: sort the parameters by name, join them as name=value with &, and make a hex HMAC-SHA256 of that string.
// lib/og-image.ts, without the SDK
import 'server-only'
import { createHmac } from 'node:crypto'
export function ogImageUrl(title: string, subtitle: string) {
const fields: Record<string, string> = {
template_id: process.env.SNAPSBREW_OG_TEMPLATE!,
variants: Buffer.from(JSON.stringify([
{ layer: 'title', text: title },
{ layer: 'subtitle', text: subtitle },
])).toString('base64'),
}
const names = Object.keys(fields).sort()
const signature = createHmac('sha256', process.env.SNAPSBREW_SIGNING_KEY!)
.update(names.map(n => `${n}=${fields[n]}`).join('&'))
.digest('hex')
const url = new URL('/signed-url/image.jpg', process.env.SNAPSBREW_URL)
for (const n of names) url.searchParams.set(n, fields[n])
url.searchParams.set('signature', signature)
return url.toString()
}
Use standard base64 with +, / and = padding. A base64url value decodes to the wrong bytes, and the instance returns a placeholder image.
Step 4: Return the URL from generateMetadata
In the page of a dynamic route, return the URL in openGraph.images and twitter.images. In Next.js 15 and later, params is a promise.
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { getPost } from '@/lib/posts'
import { ogImageUrl } from '@/lib/og-image'
type Props = { params: Promise<{ slug: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params
const post = await getPost(slug)
const image = await ogImageUrl(post.title, `${post.author} · ${post.readingTime} min read`)
return {
title: post.title,
description: post.excerpt,
openGraph: {
title: post.title,
images: [{ url: image, width: 1200, height: 630, alt: post.title }],
},
twitter: { card: 'summary_large_image', images: [image] },
}
}
getPost is your own data function. If it uses fetch, Next.js reuses the result of the same request in generateMetadata and in the page.
If the route also has an opengraph-image file, Next.js uses the file and ignores openGraph.images. Delete the file when you switch.
Step 5: Test the URL
Open the page, read the og:image tag, and request the URL with curl:
curl -sI "$(curl -s http://localhost:3000/blog/hello-world | grep -o 'og:image" content="[^"]*' | cut -d'"' -f3 | sed 's/&/\&/g')"
| Response | Meaning |
|---|---|
302 with a Location header |
The image rendered, or a cached image exists. |
200 with a small PNG |
The placeholder. The signature, the key or the template ID is wrong. |
400 |
The variants break a rule. For example, an image_url is not a public address. |
429 |
Too many requests from one IP address. The default limit is 600 a minute. |
Then paste the URL of the page into the share preview of the platform that matters most to you, for example the post composer of LinkedIn.
Make the first share fast
The first request renders the image, so the first crawler waits for the render. Crawlers have timeouts. To be safe, request each new URL one time after you publish the page. A deploy hook or a CMS webhook can do it:
// After you publish a post
await fetch(await ogImageUrl(post.title, subtitle), { redirect: 'manual' })
Long titles
The text layer has a fixed box. A long title can wrap to more lines than the design allows. Test the longest title that you have, with GET /v1/snaps/preview or the template page of your instance. If the title is too long, cut it in ogImageUrl before you sign:
const short = title.length > 90 ? `${title.slice(0, 87)}…` : title
Add images and colors
A variant can also change an image, a color or a QR code. For example, the author photo and a color for each category:
variants: [
{ layer: 'title', text: post.title },
{ layer: 'avatar', image_url: post.author.photoUrl },
{ layer: 'band', background_color: post.category.color },
]
An image_url must be a public http or https address. The instance refuses private and loopback hosts. Read Layers and variants for the full list.
Questions
- Do I need the next/og ImageResponse API for dynamic OG images?
- No.
next/ogrenders the image inside your app with JSX. A signed URL moves the render to a separate image server. Both give each page its own image. Read Dynamic OG images compared for the trade-offs. - Can I sign the URL in a client component?
- No. The signed-URL key is a secret. A person with the key can render any image on your instance. Sign the URL in
generateMetadata, a server component or a route handler. - What happens when I change the title of a post?
- The variants change, so the URL and its signature change. The next request renders a new image. The old image stays in storage until you delete it.
- Why does the URL show a gray placeholder image?
- The instance could not match the signature. Make sure that the key is active, that the template belongs to the company of the key, and that you encode the variants with standard base64, not base64url.