The user wants me to "Architect a dynamic OG image renderer leveraging edge functions, caching, and font licensing."
This is a system design and implementation request, not a specific coding problem with a single correct answer. The user wants to see how to build this system. The key components mentioned are:
Dynamic OG Image Renderer: Generating Open Graph images on the fly (likely using HTML/CSS to Image or Canvas/SVG).
Edge Functions: Running code close to the user (e.g., Vercel Edge Functions, Cloudflare Workers) for low latency.
Caching: Storing generated images to avoid re-computing and to save resources (CDN caching).
Font Licensing: Handling fonts legally and technically (self-hosting, protecting licensed files).
I need to provide a comprehensive guide that covers:
High-Level Architecture: How the pieces fit together.
Technology Stack: Specific tools (e.g., Satori for rendering, Vercel/Cloudflare for edge).
Implementation Details: Code snippets for the renderer and the caching logic.
Font Strategy: How to manage fonts securely and legally in an edge environment.
Step 1: Core Technology Choice
Renderer: satori is the industry standard for this in the JS/Edge ecosystem. It converts HTML/CSS to SVG. Then resvg-js (or similar) converts SVG to PNG. Why not Puppeteer? Puppeteer is too heavy for Edge functions usually (though some serverless platforms support it, satori is "edge-native").
Runtime: Vercel Edge Functions (Next.js Middleware or API routes) or Cloudflare Workers. I'll focus on Next.js/Vercel as it's the most common ecosystem for satori.
Step 2: The Flow
Client requests image (/api/og?title=...).
Edge Function checks Cache (CDN). If hit, return.
If miss:
a. Load Font (from blob storage or bundled).
b. Generate JSX (HTML).
c. Pass to satori -> SVG.
d. Pass to resvg -> PNG.
e. Return response with Cache-Control headers.
Step 3: Addressing "Font Licensing"
This is the tricky part. Commercial fonts usually disallow redistribution. Hosting them on a CDN to be used by a renderer is "redistribution" if not handled carefully.
Legal: Buy the license.
Technical:
Don't expose the font URL publicly to end-users (the font is used server-side to draw the image, the browser never downloads the font itself, only the resulting image).
Embedding the font binary in the edge function? Might hit size limits (1MB/50MB).
Fetching from private blob storage (R2/S3) at runtime? Adds latency.
Best practice for Edge: Convert font to base64 or ArrayBuffer and include it in the bundle if size permits, or fetch from a high-speed private bucket. I will emphasize that the font is processed server-side, so the user never accesses the .ttf directly, which helps with licensing compliance (preventing casual download).
Step 5: Structuring the Response
I should structure the answer as a "Blueprint" or "Architecture Guide".
Phase 1: The Stack (Satori, Resvg, Next.js).
Phase 2: The Font Pipeline (Licensing constraints, loading techniques).
Phase 3: The Renderer Code (Actual implementation).
Phase 4: Caching Strategy (Headers).
Drafting the Content (Mental Outline):
Intro: Why Edge + Satori.
Font Licensing: This needs to be prominent. The renderer acts as a "shield". Users download pixels, not vectors.
Code Example:
Import satori.
Fetch font (inter or a custom one).
Define the HTML/JSX.
Convert to SVG -> PNG.
Set Headers.
Architecture Diagram: I will describe it textually.
Refining the Font Licensing Section:
Many people miss that simply hosting a font file via @font-face violates licenses if they don't allow web embedding. However, since we are rendering a PNG, we are effectively publishing an image, not the software (font). I need to make this distinction. The font file stays in the Edge Function's memory/disk, never sent to the client.
Refining Caching:
Edge functions are stateless. Caching must happen at the HTTP level (CDN) or a Key-Value store (KV). HTTP headers are the easiest and most efficient for OG images.
Self-Correction during thought process:
Initial thought: Use Puppeteer.
Correction: Too heavy for Edge. Use Satori.
Initial thought: Load fonts via fetch inside the function every time.
Correction: Too slow. Bundle small fonts or cache the fetch in memory/KV.
Let's write the response. I will assume a Next.js/App Router environment as it's the standard for this architecture.
Plan:
Architecture Overview: The request flow.
Font Compliance Strategy: Protecting the IP.
Implementation (Next.js + Satori): The code.
Caching Layers: CDN vs Browser.
Let's build the code snippet mentally.
new Response(imageBuffer, { headers: { 'Content-Type': 'image/png', 'Cache-Control': ... } })
Font loading: fs.readFileSync (if possible in bundle) or fetch. In Edge, fs isn't usually available. Use fetch to get array buffer or bundle as base64 string. Since I can't provide the font file, I'll simulate the loader or use a standard open-source font for the example, explaining how to swap it for a licensed one.
Font Licensing nuance: I must mention that while rendering to PNG protects the vector data, some "super strict" EULAs might still have clauses about server usage, but generally, rasterization is the safe path.
Let's go.
This architecture leverages Vercel Edge Functions (or Cloudflare Workers) and Satori (HTML-to-SVG converter) to generate Open Graph images dynamically.
This approach solves the "heavy runtime" problem of browser-based screenshotting by using a lightweight SVG renderer that runs directly on the Edge.
1. High-Level Architecture
The system consists of three distinct layers:
The Edge Renderer: A serverless function that accepts JSON/Query params, injects them into an HTML template, and converts it to an SVG/PNG using Satori and Resvg.
The Asset Layer: Where your licensed fonts are hosted (preferably on a high-speed blob store or bundled with the function).
The Cache Layer: Vercel’s Edge Network (or CDN) to serve stale-while-revalidate content.
2. Font Licensing & Compliance Strategy
This is the most critical business logic. Licensed fonts (like those from Monotype or Hoefler&Co) often restrict "Server Embedding" or require distinct licenses for it.
Subsetting (The Optimization): You cannot ship a 2MB font file to the edge. You must use a tool like pyftsubset (fonttools) to extract only the glyphs needed for the specific text.
The "Shield" Architecture: Never expose the raw font file URL to the public.
The font is downloaded by the Edge Function into memory.
It is used purely for calculation/rasterization.
The output is an Image (Rasterized).
Legal Note: Rasterizing a font into a bitmap image is generally covered by standard desktop/web licenses, whereas serving the vector file (WOFF/WOFF2) is not.
3. Implementation (Next.js + Satori)
We will use Satori because it converts HTML/CSS to SVG using a pure JavaScript engine, making it compatible with Edge Runtimes (which lack a DOM).
A. The Edge Function (app/api/og/route.tsx)
tsx
import { ImageResponse } from '@vercel/og';
import { NextRequest } from 'next/server';
export const config = {
runtime: 'edge',
};
// 1. Font Loading Strategy
// Ideally, fetch this from a CDN or Blob Storage.
// For this demo, we assume the font is converted to ArrayBuffer.
async function loadFont(subsetText: string) {
// In a real app, you would dynamically subset here or load a pre-subsetted chunk.
// For speed, we load a pre-subsetted file stored in the repo or KV store.
const fontUrl = new URL('../../assets/Inter-Bold.ttf', import.meta.url);
const fontData = await fetch(fontUrl).then((res) => res.arrayBuffer());
return fontData;
}
export default async function handler(req: NextRequest) {
const { searchParams } = new URL(req.url);
// 2. Dynamic Inputs
const title = searchParams.get('title') || 'Default Title';
const subtitle = searchParams.get('subtitle') || 'Generated at the Edge';
// 3. Load Font
// Optimization: Cache this fetch in memory if the function stays warm
const fontData = await loadFont(title);
// 4. Generate Image
try {
return new ImageResponse(
(
<div
style={{
height: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#0f172a', // Slate 900
backgroundImage: 'radial-gradient(circle at 25px 25px, #334155 2%, transparent 0%), radial-gradient(circle at 75px 75px, #334155 2%, transparent 0%)',
backgroundSize: '100px 100px',
padding: '80px',
}}
>
<div
style={{
display: 'flex',
fontSize: 80,
fontFamily: 'Inter', // Must match font loading below
fontWeight: 900,
color: 'white',
lineHeight: 1.2,
textAlign: 'center',
textShadow: '0 10px 30px rgba(0,0,0,0.5)',
}}
>
{title}
</div>
<div
style={{
marginTop: 40,
display: 'flex',
fontSize: 30,
color: '#94a3b8',
fontFamily: 'Inter',
}}
>
{subtitle}
</div>
</div>
),
{
width: 1200,
height: 630,
fonts: [
{
name: 'Inter',
data: fontData,
weight: 900,
style: 'normal',
},
],
// 5. Caching Headers (CRITICAL)
headers: {
'Cache-Control': 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=3600',
'CDN-Cache-Control': 'max-age=86400', // Tell Vercel/Cloudflare to cache it for a day
},
}
);
} catch (e: any) {
console.error(e);
return new Response(`Failed to generate image`, { status: 500 });
}
}
4. The Caching Strategy
We need a multi-tiered caching strategy to ensure the Edge Function doesn't run expensive font parsing logic on every hit.
Layer 1: The CDN (Vercel Edge Network / Cloudflare)
We set s-maxage=86400 (1 day).
We use stale-while-revalidate. This ensures that if the cache expires, the CDN serves the old image immediately while triggering the function in the background to refresh it.
Result: The user never waits for the renderer after the first hit.
Layer 2: The Function Cache (In-Memory/KV)
Font fetching is slow.
Optimization: Store the font ArrayBuffer in a Key-Value store (like Vercel KV or Cloudflare KV) keyed by the text content (if dynamically subsetting) or just a static key if using a pre-subset font.
Code Pattern:
typescript
// Pseudo-code for caching the font buffer
let fontBuffer = await kv.get('font-main');
if (!fontBuffer) {
fontBuffer = await fetch(url).then(r => r.arrayBuffer());
await kv.set('font-main', fontBuffer, { ex: 604800 }); // Cache for 1 week
}
5. Advanced: Dynamic Font Subsetting Pipeline
If you are strictly licensed and need to minimize bandwidth, you can implement a dynamic subsetting layer using Harfbuzz compiled to WASM.
Request: /api/og?title=Hello
Subsetting: The edge function takes the string "Hello".
WASM: It slices the full font binary to only include H, e, l, o.
Result: The font data passed to Satori is 5KB instead of 2MB.
Tradeoff: This adds ~100ms latency but ensures 100% license compliance regarding data transfer.
6. Summary of Tech Stack
Component
Technology Choice
Why?
Renderer
Satori (Vercel)
Converts HTML/CSS to SVG. No headless browser needed. Extremely fast.
Runtime
Edge Functions
Lowest latency, global distribution.
Fonts
Self-Hosted WOFF2
Compliance. Load via fetch into memory.
Image Format
SVG -> PNG (Resvg)
While Satori outputs SVG, social crawlers prefer PNG/JPEG. @vercel/og handles this conversion automatically using Resvg (Rust-WASM).
Cache
HTTP Headers (CDN)
stale-while-revalidate is the gold standard for dynamic assets.