Immagini OG in Next.js senza una edge route
Genera immagini OG per l'App Router di Next.js con l'API ospitata di FastOG: nessuna edge route, nessun bundle satori nella tua distribuzione e nessun costo di rendering per richiesta sul tuo piano. Crea una chiave API nella dashboard e il Free OG Image Tester (tester gratuito per immagini OG) ti mostra l'anteprima dell'immagine prima ancora di scrivere una riga di codice. Questa guida crea immagini Open Graph dinamiche con URL firmati HMAC, direttamente dall'App Router.
Quick Start
1. Crea l'utility per la firma
// 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 le variabili d'ambiente
# .env.local
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here
Pattern 1: Metadata API (consigliato)
// 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: Proxy tramite API Route
Usalo se vuoi mettere in cache le immagini OG o aggiungere logica personalizzata.
// 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 },
);
}
}
Utilizzo nei template:
<meta property="og:image" content={`/api/og?title=${encodeURIComponent(post.title)}`} />
Pattern 3: Server Component Direct
// 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>
);
}
Esempio E-commerce
// 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",
},
};
}
Profilo Utente (Template Blog)
FastOG non ha un template profile — usa blog per una card in stile profilo, passando il nome dell'utente come title, la bio come subtitle e il nome come author.
// 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",
},
};
}
Errori comuni
Firmare byte diversi da quelli che invii
La firma copre GET/api/v1/og più un newline più la query canonica — le coppie enc(key)=enc(value) ordinate di ogni parametro tranne s, inclusi key. Costruisci l'URL finale da quelle stesse coppie codificate, altrimenti il server restituisce 401 invalid_signature.
Esporre il segreto HMAC nel codice client
❌ Sbagliato:
// In client component
const ogUrl = generateSignedOgUrl(params, {
hmacSecret: process.env.NEXT_PUBLIC_HMAC_SECRET,
});
✅ Corretto:
// In server component or API route (never expose to client)
export async function generateMetadata() {
const ogUrl = generateSignedOgUrl(params);
}
Quando usare next/og o @vercel/og invece
Entrambi gli approcci generano un PNG all'interno della tua app. Scegli in base a cosa stai renderizzando e con quale frequenza.
next/og / ImageResponse |
API ospitata FastOG | |
|---|---|---|
| Dove viene creato il PNG | La tua edge function, a ogni richiesta | Il renderer di FastOG, poi in cache |
| Costo del bundle | Spedisce satori + resvg all'edge | Nessuno nella tua app |
| Cold start | La prima richiesta dopo l'inattività lo paga | Nessuno |
| Font ed emoji | Li includi e li riduci tu | Inclusi |
| Cataloghi di prodotti | Un template di copertina, costruito a mano | 68 template guidati dai parametri di query |
| Dati di prezzo/promo/stock | Li recuperi e li impagini tu | Passati come parametri, renderizzati lato server |
| Caching | Configuri tu gli header | Content-addressed e messo in cache da FastOG |
| Firma | n/a | HMAC-SHA256, così gli URL non possono essere generati da terze parti |
Mantieni next/og quando la copertina è una card una tantum, puramente tipografica, e la route esiste già. Ricorri all'API ospitata quando la copertina deve trasportare dati di prodotto live (prezzo, badge di sconto, valutazione, stock), quando il catalogo è grande, o quando spedire satori all'edge è proprio ciò che stai cercando di evitare.