Generate OG Images in Next.js — Dynamic og:image API

Generate OG images in Next.js with FastOG's credit-based API — sign up free for 100 credits (create your API key in the dashboard), and the Free OG Image Tester previews your image before you write a line of code. This guide shows you how to build dynamic Open Graph images with HMAC-signed URLs, straight from the Next.js App Router.

Quick Start

1. Create the signer utility

javascript
// lib/og-image-signer.js
import crypto from "crypto";

export function generateSignedOgUrl(params, options = {}) {
    const {
        baseUrl = "https://fastog.com/api/v1/og",
        apiKey = process.env.FASTOG_API_KEY,
        hmacSecret = process.env.FASTOG_HMAC_SECRET,
    } = options;

    if (!apiKey || !hmacSecret) {
        throw new Error("Missing FASTOG_API_KEY or FASTOG_HMAC_SECRET");
    }

    const timestamp = Math.floor(Date.now() / 1000);
    const url = new URL(baseUrl);

    for (const [key, value] of Object.entries(params)) {
        url.searchParams.set(key, value);
    }

    const apiKey = apiKey;
    const path = url.pathname;
    const message = `GET${path}${timestamp}${apiKey}`;

    const signature = crypto
        .createHmac("sha256", hmacSecret)
        .update(message)
        .digest("hex");

    url.searchParams.set("key", apiKey);
    url.searchParams.set("s", signature);
    url.searchParams.set("t", timestamp);

    return url.toString();
}

2. Set up environment variables

bash
# .env.local
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here

Pattern 1: Metadata API (Recommended)

typescript
// app/blog/[slug]/page.tsx
import { generateSignedOgUrl } from "@/lib/og-image-signer";
import { getPost } from "@/lib/posts";

interface PageProps {
    params: Promise<{ slug: string }>;
}

export async function generateMetadata({ params }: PageProps) {
    const { slug } = await params;
    const post = await getPost(slug);

    const ogImageUrl = generateSignedOgUrl({
        template: "blog",
        title: post.title,
        subtitle: post.excerpt,
        author: post.author.name,
    });

    return {
        title: post.title,
        description: post.excerpt,
        openGraph: {
            title: post.title,
            description: post.excerpt,
            images: [
                {
                    url: ogImageUrl,
                    width: 1200,
                    height: 630,
                    alt: post.title,
                },
            ],
            type: "article",
        },
        twitter: {
            card: "summary_large_image",
            images: [ogImageUrl],
        },
    };
}

export default async function BlogPost({ params }: PageProps) {
    const { slug } = await params;
    const post = await getPost(slug);

    return (
        <article>
            <h1>{post.title}</h1>
            <p>{post.excerpt}</p>
        </article>
    );
}

Pattern 2: API Route Proxy

Use this if you want to cache OG images or add custom logic.

typescript
// app/api/og/route.ts
import { NextRequest, NextResponse } from "next/server";
import { generateSignedOgUrl } from "@/lib/og-image-signer";

export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url);
        const title = searchParams.get("title");
        const template = searchParams.get("template") || "default";

        if (!title) {
            return NextResponse.json(
                { error: "Missing title parameter" },
                { status: 400 },
            );
        }

        const ogImageUrl = generateSignedOgUrl({
            template,
            title,
        });

        // Option 1: Redirect to FastOG
        return NextResponse.redirect(ogImageUrl);

        // Option 2: Fetch and return image(for caching)
        // const response = await fetch(ogImageUrl);
        // const imageBuffer = await response.arrayBuffer();
        // return new NextResponse(imageBuffer, {
        //     headers: {
        //         'Content-Type': 'image/png',
        //         'Cache-Control': 'public, max-age=31536000, immutable',
        //     },
        // });
    } catch (error) {
        console.error("OG image generation failed:", error);
        return NextResponse.json(
            { error: "Failed to generate OG image" },
            { status: 500 },
        );
    }
}

Usage in templates:

typescript
<meta property="og:image" content={`/api/og?title=${encodeURIComponent(post.title)}`} />

Pattern 3: Server Component Direct

typescript
// app/blog/[slug]/page.tsx
import { generateSignedOgUrl } from '@/lib/og-image-signer';

export default async function BlogPost({ params }) {
    const post = await getPost(params.slug);

    const ogImageUrl = generateSignedOgUrl({
        template: 'blog',
        title: post.title,
    });

    return (
        <article>
            <head>
                <meta property="og:image" content={ogImageUrl} />
                <meta property="og:title" content={post.title} />
            </head>
            {/* ... post content ... */}
        </article>
    );
}

E-commerce Example

typescript
// app/products/[id]/page.tsx
import { generateSignedOgUrl } from "@/lib/og-image-signer";

export async function generateMetadata({ params }) {
    const { id } = await params;
    const product = await getProduct(id);

    const ogImageUrl = generateSignedOgUrl({
        template: "ecommerce",
        title: product.name,
        price: product.price,
        image: product.image,
    });

    return {
        openGraph: {
            title: product.name,
            description: product.description,
            images: [{ url: ogImageUrl, width: 1200, height: 630 }],
            type: "product",
        },
    };
}

User Profile Example

typescript
// app/users/[username]/page.tsx
import { generateSignedOgUrl } from "@/lib/og-image-signer";

export async function generateMetadata({ params }) {
    const { username } = await params;
    const user = await getUser(username);

    const ogImageUrl = generateSignedOgUrl({
        template: "profile",
        name: user.name,
        avatar: user.avatarUrl,
        bio: user.bio,
    });

    return {
        openGraph: {
            title: `${user.name} - Profile`,
            description: user.bio,
            images: [{ url: ogImageUrl, width: 1200, height: 630 }],
            type: "profile",
        },
    };
}

Common Pitfalls

Wrong:

javascript
const apiKey = apiKey; // "sk_abc123..."

Correct:

javascript
const apiKey = apiKey; // "sk_abc12"

Timestamp in Milliseconds

Wrong:

javascript
const timestamp = Date.now(); // 1722718800000

Correct:

javascript
const timestamp = Math.floor(Date.now() / 1000); // 1722718800

Exposing HMAC Secret in Client Code

Wrong:

javascript
// In client component
const ogUrl = generateSignedOgUrl(params, {
    hmacSecret: process.env.NEXT_PUBLIC_HMAC_SECRET,
});

Correct:

javascript
// In server component or API route(never expose to client)
export async function generateMetadata() {
    const ogUrl = generateSignedOgUrl(params);
}

Full API Reference

Related

Try it free — no signup required

Preview and test dynamic OG images in seconds.

Open the Free OG Image Tester