# Dynamic Open Graph images in Next.js

> Generate og:image cards in the Next.js App Router from a page you design in HTML and CSS: a signed Shotfly URL in generateMetadata, cached, secret kept server-side.

Design the card as an ordinary page in your Next.js app, then point `og:image` at a signed Shotfly URL that captures it at 1200 × 630. The card can use any CSS, font or component your site already has. The secret key stays on the server, and social networks fetch the image from Shotfly.

## When is this better than next/og?

Next.js's built-in `ImageResponse` from `next/og` draws JSX to an image inside your app, with no external request, but it is not a complete CSS implementation: its documentation lists flexbox and a subset of CSS properties ([Next.js docs](https://nextjs.org/docs/app/api-reference/functions/image-response), read 2026-12-01). A screenshot fits better when the card needs CSS that only a browser renders, or when the card is an existing page.

## 1. Make the card page

```tsx
import type { Metadata } from 'next'

type Props = { params: Promise<{ slug: string }> }

// Only Shotfly needs this page; keep it out of search results.
export const metadata: Metadata = { robots: { index: false } }

// Captured at 1200 × 630. Use the same CSS and fonts as the rest of your site.
export default async function OgCard({ params }: Props) {
  const { slug } = await params
  return (
    <main
      style={{
        width: 1200,
        height: 630,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 80,
        background: '#0b0b0c',
        color: '#fff',
        fontFamily: 'system-ui, sans-serif',
      }}
    >
      <p style={{ fontSize: 28, opacity: 0.7 }}>your.site/blog</p>
      <h1 style={{ fontSize: 72, lineHeight: 1.1 }}>{slug.replaceAll('-', ' ')}</h1>
    </main>
  )
}
```

## 2. Sign the screenshot URL

```ts
import { createHmac } from 'node:crypto'

const API = 'https://api.shotfly.dev'

const rfc3986 = (s: string) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)

/** A signed screenshot URL for og:image. Server code only: it reads the secret key. */
export function ogImageUrl(pageUrl: string): string {
  const params: Record<string, string> = {
    url: pageUrl,
    viewport_width: '1200',
    viewport_height: '630',
    format: 'png',
    cache_ttl: '604800', // a week; cache hits are free
    access_key: process.env.SHOTFLY_PUBLIC_KEY!,
  }
  const canonical = Object.keys(params)
    .sort()
    .map((k) => `${rfc3986(k)}=${rfc3986(params[k]!)}`)
    .join('&')
  const signature = createHmac('sha256', process.env.SHOTFLY_SECRET_KEY!)
    .update(canonical)
    .digest('hex')
  return `${API}/v1/screenshot?${new URLSearchParams({ ...params, signature })}`
}
```

Put `SHOTFLY_PUBLIC_KEY` and `SHOTFLY_SECRET_KEY` in `.env.local` and in your host's environment settings. Never give them the `NEXT_PUBLIC_` prefix, which would ship them to the browser.

## 3. Use it in generateMetadata

```tsx
import type { Metadata } from 'next'
import { ogImageUrl } from '@/lib/shotfly'

type Props = { params: Promise<{ slug: string }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const image = ogImageUrl(`https://your.site/og/${slug}`)
  return {
    title: slug,
    openGraph: { images: [{ url: image, width: 1200, height: 630 }] },
    twitter: { card: 'summary_large_image', images: [image] },
  }
}

export default async function Post({ params }: Props) {
  const { slug } = await params
  return <h1>{slug}</h1>
}
```

## How are the images cached, and what do they cost?

Each distinct URL is rendered once and then served from cache for `cache_ttl` seconds: a week in this example, at most 30 days. Cache hits are free, and signed images carry a public `Cache-Control` header, so CDNs can keep them too. To refresh a card after you change it, change its URL, for example by adding `?v=2` to the card page address.

More on the use case: [Open Graph image API](https://shotfly.dev/use-cases/og-image). Signing in other languages: [authentication and signed URLs](https://shotfly.dev/docs/authentication#signing).

---

Source: https://shotfly.dev/docs/guides/nextjs-og-image · Last updated 2026-12-01
