# How to generate dynamic OG images in Next.js

Source: https://snapsbrew.com/guides/nextjs-og-images

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](https://amedina.me), maintainer of Snapsbrew. Published 27 November 2026. Last updated 27 November 2026.

On this page

- [What you need](#what-you-need)
- [How a signed URL works](#how-a-signed-url-works)
- [Step 1: Design the template](#step-1-design-the-template)
- [Step 2: Get a signed-URL key](#step-2-get-a-signed-url-key)
- [Step 3: Sign the URL on the server](#step-3-sign-the-url-on-the-server)
- [Step 4: Return the URL from generateMetadata](#step-4-return-the-url-from-generatemetadata)
- [Step 5: Test the URL](#step-5-test-the-url)
- [Make the first share fast](#make-the-first-share-fast)
- [Long titles](#long-titles)
- [Add images and colors](#add-images-and-colors)

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](https://snapsbrew.com/docs/getting-started/installation-docker.md).
- 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

1. On your instance, open `/templates/new`.
2. Pick a starter template, or start from an empty canvas.
3. Set the canvas to the `open_graph` preset. It is 1200x630 pixels.
4. Add a text layer with the key `title`. Add a second text layer with the key `subtitle`.
5. 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

1. Open **Account > Developers**.
2. In **Signed URL API keys**, click **Generate new key**.
3. 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.

```bash
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.

```ts
// 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.

```ts
// 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.

```tsx
// 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:

```bash
curl -sI "$(curl -s http://localhost:3000/blog/hello-world | grep -o 'og:image" content="[^"]*' | cut -d'"' -f3 | sed 's/&amp;/\&/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:

```ts
// 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:

```ts
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:

```ts
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](https://snapsbrew.com/docs/using-snapsbrew/layers-and-variants.md) for the full list.

## Questions

Do I need the next/og ImageResponse API for dynamic OG images?

No. `next/og` renders 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](https://snapsbrew.com/blog/dynamic-og-images-compared.md) 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.

## Related pages

- [How to generate dynamic OG images in Nuxt](https://snapsbrew.com/guides/nuxt-og-images.md)
- [Dynamic OG images compared: Satori, a headless browser or a template API](https://snapsbrew.com/blog/dynamic-og-images-compared.md)
- [Signed URLs](https://snapsbrew.com/product/signed-url.md)
- [Docs: Signed URLs](https://snapsbrew.com/docs/using-snapsbrew/signed-urls.md)
- [Docs: SDKs for JavaScript, PHP, Python and Ruby](https://snapsbrew.com/docs/sdks/overview.md)

## Run it on your own server

Docker Compose starts the app, the queue, MySQL, Redis and the renderer together.

[Self-host it](https://snapsbrew.com/docs/getting-started/installation-docker.md) [View on GitHub](https://github.com/amedina068/snapsbrew)

```bash
git clone https://github.com/amedina068/snapsbrew.git
cd snapsbrew
cp .env.docker.example .env   # then fill in .env
docker compose up -d --build
```
