Every pin my app produces is a 1000×1500 image drawn on the server from JSX: no headless browser, no canvas code, no design tool. The renderer is Satori, which ships inside Next.js as ImageResponse, and after a few weeks of using it for something much bigger than Open Graph cards, I have a list of things I wish I'd known on day one.

This post walks through the full pipeline: loading fonts, preparing photos, the layout rules Satori imposes, turning the result into a JPEG, and serving it.

Satori in one paragraph

Satori takes a React element tree with inline styles and returns an SVG. It implements its own layout engine (Yoga, the flexbox engine from React Native) and its own text shaping, which is why it's fast and runs in any JavaScript runtime. next/og wraps it as ImageResponse, which also rasterises the SVG to PNG and gives you a standard Response.

import { ImageResponse } from "next/og"; const res = new ImageResponse(element, { width: 1000, height: 1500, fonts: await loadFonts(), }); const png = Buffer.from(await res.arrayBuffer()); 

You can use ImageResponse anywhere on the server, not only as the return value of a route. I call it from a plain function, renderPin(pin, slide), which is used by the image route, the ZIP export and the code that posts to Pinterest.

Fonts: load once, from files you ship

Satori has no system fonts. You pass every font as raw bytes, with its family name, weight and style. It reads TTF, OTF and WOFF, but not WOFF2, which matters if you take fonts from @fontsource packages: copy the .woff files, not the .woff2 ones.

I keep the files in assets/fonts and load them once per server instance:

type LoadedFont = { name: string; data: Buffer; weight: 400 | 500 | 600 | 700 | 800 | 900; style: "normal" | "italic" }; let fontsPromise: Promise<LoadedFont[]> | null = null; function loadFonts() { fontsPromise ??= Promise.all( FONT_FILES.map(async (f) => ({ name: f.family, weight: f.weight, style: f.style ?? "normal", data: await fs.readFile(path.join(process.cwd(), "assets", "fonts", f.file)), })), ); return fontsPromise; } 

Caching the promise rather than the result means concurrent first requests share one read.

On Vercel there's a catch: files read with fs at runtime are not traced into the function bundle unless you say so. Without this, everything works locally and every image fails in production:

// next.config.ts const nextConfig: NextConfig = { serverExternalPackages: ["sharp"], outputFileTracingIncludes: { "/api/**": ["./assets/fonts/**"], }, }; 

If an italic word is ever drawn in the upright face, check that you registered the italic file with style: "italic" under the same family name. Satori picks the face by family, weight and style; if none matches, it falls back to whatever it has.

Photos: crop with sharp first, then hand Satori a data URI

Satori can fetch remote images by URL, but I don't let it. Blog photos are often WebP or AVIF, often 4000 pixels wide, and Satori would embed the whole thing. Instead, every photo is cropped to the exact box it fills, re-encoded as a small JPEG and passed as a data URI:

export async function coverDataUri(userId: string, src: string, width: number, height: number) { const hash = createHash("sha1").update(`${userId}|${src}|${width}x${height}`).digest("hex"); const cached = path.join(CACHE_DIR, `${hash}.jpg`); let jpeg: Buffer; try { jpeg = await fs.readFile(cached); } catch { try { jpeg = await sharp(await loadImage(userId, src)) .rotate() // respect EXIF orientation .resize(width, height, { fit: "cover", position: sharp.strategy.attention }) .jpeg({ quality: 84 }) .toBuffer(); } catch { return null; // the template draws a flat colour instead } // The cache is an optimisation; a read-only or full disk must not break rendering. await fs.mkdir(CACHE_DIR, { recursive: true }).then(() => fs.writeFile(cached, jpeg)).catch(() => {}); } return `data:image/jpeg;base64,${jpeg.toString("base64")}`; } 

Two details I like here. sharp.strategy.attention crops towards the most interesting region of the photo (fine detail, colour saturation, skin tones) instead of the centre, which helps a lot when a landscape blog photo has to become a tall slot. And each template declares its photo slots with their sizes, so the crop matches the layout exactly:

const images = await Promise.all( template.slots.map((slot, i) => { const src = pin.images[i] ?? pin.images[0]; return src ? coverDataUri(pin.userId, src, slot.w, slot.h) : Promise.resolve(null); }), ); 

On serverless the cache lives in the temp directory, so it only survives while the instance is warm. That's fine: it exists because the editor re-renders the same pin many times while someone tries layouts.

The layout rules Satori imposes

Satori is not a browser. These are the rules that bit me, and they're now written at the top of my shared template file:

  • Only flexbox. No grid, no floats. Absolute positioning works inside a relative parent, which covers overlays.
  • Every element with more than one child needs display: "flex". Satori throws otherwise.
  • Text never wraps or shrinks by itself in a way you control. If a headline must fill a box, you have to measure it yourself. I measure with the real glyph widths from the font files (the next article in this series).
  • undefined style values can break rendering. Conditional styles like { textShadow: maybeShadow } are common in JSX, so I strip them:
export const css = (style: CSSProperties): CSSProperties => Object.fromEntries(Object.entries(style).filter(([, v]) => v !== undefined)) as CSSProperties; 
  • Decorations should be deterministic. My hand-drawn marks (a highlighter stroke, a sketched box) are small SVGs with a bit of randomness. If that randomness came from Math.random(), every preview would look different. A seed from the text keeps them stable:
export function seedOf(text: string): number { let h = 2166136261; for (const ch of text) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); return h >>> 0; } 

SVGs, like photos, go in as <img src="data:image/svg+xml;...">. Satori draws them happily.

PNG out, JPEG to the world

ImageResponse gives you a PNG. For pins with photos, that's large, so the last step converts it:

let png = Buffer.from(await res.arrayBuffer()); // JPEG is roughly a tenth of the PNG's size for photo-heavy pins. return sharp(png).jpeg({ quality: 90, chromaSubsampling: "4:4:4" }).toBuffer(); 

The "roughly a tenth" is what I saw on my own pins, so measure yours. The chromaSubsampling: "4:4:4" is not optional for text-heavy images: the default 4:2:0 halves the colour resolution, and thin red letters on a white background get visibly smeared edges.

Post-processing with sharp: checking a patch before writing on it

Having the image as a buffer also lets me do things Satori can't. Pins get a small signature (a handle or site name) at the bottom left, but only when the spot is calm. Writing small text over busy photo detail looks bad, so I cut out the patch, check the standard deviation of each colour channel and skip the signature if it's noisy:

const stats = await sharp(await sharp(png).extract(box).toBuffer()).stats(); const [r, g, b] = stats.channels; if ([r, g, b].some((c) => c.stdev > 14)) return png; // too busy: leave it out const light = 0.2126 * r.mean + 0.7152 * g.mean + 0.0722 * b.mean > 140; // ...render a small strip with ImageResponse in dark or light ink, then composite it 

Note the double sharp call: stats() looks at the whole input, so the patch is extracted into its own buffer first. The luminance check picks dark or light ink for the text.

Serving it

The image route renders on demand and lets the editor preview another design without saving it:

export const GET = route(async (req: Request, ctx: { params: Promise<{ id: string }> }) => { const { id } = await ctx.params; const pin = await loadOwnPin(id); // 404 unless it belongs to the signed-in user const q = new URL(req.url).searchParams; const image = await renderPin({ ...pin, templateId: q.get("templateId") ?? pin.templateId, paletteId: q.get("paletteId") ?? pin.paletteId, fontId: q.get("fontId") ?? pin.fontId, }); return new Response(new Uint8Array(image), { headers: { "content-type": "image/jpeg", // The URL carries the pin's version, so a given URL never changes. "cache-control": q.has("v") ? "private, max-age=31536000, immutable" : "no-store", }, }); }); 

The v parameter is the trick that makes caching safe: the UI adds the pin's version to the URL, so a saved pin gets a new URL on every edit and old URLs can be cached forever.

Takeaways

  • ImageResponse from next/og is a general server-side renderer, not just for OG images. Call it from any server function.
  • Ship your fonts as WOFF/TTF/OTF (not WOFF2), load them once, and trace them into the bundle with outputFileTracingIncludes.
  • Crop and compress photos with sharp before Satori sees them; strategy.attention makes better crops than the centre.
  • Plan for flexbox only, display: flex on every multi-child element, no undefined styles, and seeded randomness.
  • Convert to JPEG with 4:4:4 chroma for text, and version your image URLs so they can be cached forever.

This is the renderer behind PinCyborg's pin designs. Next in the series: fitting headlines to their box when the renderer won't do it for you.

Drafted with help from an AI assistant and checked against the real code.