Tema

Imágenes OG en Next.js sin una ruta edge

Genera imágenes OG para el App Router de Next.js con la API alojada de FastOG: sin ruta edge, sin bundle de satori en tu despliegue y sin coste de renderizado por petición en tu plan. Crea una clave de API en el dashboard, y el Probador de imágenes OG gratuito previsualiza tu imagen antes de que escribas una línea de código. Esta guía crea imágenes Open Graph dinámicas con URLs firmadas con HMAC, directamente desde el App Router.

Inicio rápido

1. Crea la utilidad de firma

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");
    }

    // RFC-3986 percent-encoding: keep A-Za-z0-9-._~
    const enc = (s) =>
        encodeURIComponent(s).replace(
            /[!'()*]/g,
            (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(),
        );

    // Every query param except the signature, INCLUDING key
    const all = { ...params, key: apiKey };

    // Canonical query: sorted enc(key)=enc(value) pairs joined with &
    const pairs = [];
    for (const [k, v] of Object.entries(all)) {
        for (const vv of Array.isArray(v) ? v : [v]) {
            pairs.push(`${enc(k)}=${enc(vv)}`);
        }
    }
    pairs.sort();
    const canonical = pairs.join("&");

    // Sign the exact bytes the server will verify
    const signature = crypto
        .createHmac("sha256", hmacSecret)
        .update(`GET/api/v1/og\n${canonical}`)
        .digest("hex");

    // Build the URL from the same pairs so bytes match the canonical form
    const url = new URL(baseUrl);
    for (const [k, v] of Object.entries(all)) {
        for (const vv of Array.isArray(v) ? v : [v]) {
            url.searchParams.append(Array.isArray(v) ? `${k}[]` : k, vv);
        }
    }
    url.searchParams.set("s", signature);

    return url.toString();
}

2. Configura las variables de entorno

bash
# .env.local
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here
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>
    );
}

Patrón 2: Proxy en una ruta de API

Usa esto si quieres cachear las imágenes OG o añadir lógica personalizada.

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 },
        );
    }
}

Uso en las plantillas:

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

Patrón 3: Server Component directo

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>
    );
}

Ejemplo de comercio electrónico

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",
        },
    };
}

Perfil de usuario (plantilla de blog)

FastOG no tiene una plantilla profile; usa blog para una tarjeta con estilo de perfil, pasando el nombre del usuario como title, la biografía como subtitle y el nombre como author.

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: "blog",
        title: user.name,
        subtitle: user.bio,
        author: user.name,
    });

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

Errores comunes

Firmar bytes distintos de los que envías

La firma cubre GET/api/v1/og más un salto de línea más la consulta canónica: los pares enc(key)=enc(value) ordenados de cada parámetro excepto s, incluido key. Construye la URL final a partir de esos mismos pares codificados, o el servidor devolverá 401 invalid_signature.

Exponer el secreto HMAC en el código del cliente

❌ Incorrecto:

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

✅ Correcto:

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

Cuándo usar next/og o @vercel/og en su lugar

Ambos enfoques renderizan un PNG dentro de tu aplicación. Elige según lo que estés renderizando y con qué frecuencia.

next/og / ImageResponse API alojada de FastOG
Dónde se genera el PNG Tu edge function, por petición El renderizador de FastOG, luego se cachea
Coste del bundle Envía satori + resvg al edge Ninguno en tu aplicación
Arranque en frío La primera petición tras la inactividad lo paga Ninguno
Fuentes y emoji Los empaquetas y los subseteas tú Incluidos
Catálogos de productos Una plantilla de portada, construida a mano 68 plantillas controladas por parámetros de consulta
Datos de precio/promo/stock Los obtienes y los maquetas tú mismo Se pasan como parámetros, se renderizan en el servidor
Caché Configuras las cabeceras Direccionada por contenido y cacheada por FastOG
Firma n/a HMAC-SHA256, para que terceros no puedan acuñar URLs

Mantén next/og cuando la portada sea una tarjeta puntual, puramente tipográfica, y la ruta ya exista. Recurre a la API alojada cuando la portada tenga que llevar datos de producto en vivo (precio, insignia de oferta, valoración, stock), cuando el catálogo sea grande o cuando enviar satori al edge sea justo lo que intentas evitar.

Referencia completa de la API

Pruébalo gratis: no se requiere registro

Previsualiza y prueba imágenes OG dinámicas en segundos.

Abrir el probador gratuito de imágenes OG

A BeCaSimulations site