惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
K
Kaspersky official blog
L
LangChain Blog
有赞技术团队
有赞技术团队
V
Visual Studio Blog
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
美团技术团队
Vercel News
Vercel News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
G
Google Developers Blog
宝玉的分享
宝玉的分享
月光博客
月光博客
爱范儿
爱范儿
The Register - Security
The Register - Security
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
F
Full Disclosure
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
WordPress大学
WordPress大学
D
Docker
Y
Y Combinator Blog
N
News and Events Feed by Topic
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recorded Future
Recorded Future
IT之家
IT之家
C
CXSECURITY Database RSS Feed - CXSecurity.com
Security Latest
Security Latest
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
D
DataBreaches.Net
Recent Announcements
Recent Announcements
博客园 - Franky
Google DeepMind News
Google DeepMind News
小众软件
小众软件
B
Blog RSS Feed
I
InfoQ
Attack and Defense Labs
Attack and Defense Labs
云风的 BLOG
云风的 BLOG

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Next.js Dynamic OG Images: Fix the Turbopack CPU Hang
Iurii Roguli · 2026-05-26 · via DEV Community

My portfolio site had one static og-image.jpeg for every page. When someone shared a blog post on LinkedIn, the preview showed the same generic image as the homepage. OG images are part of the broader technical SEO foundation I build into every project. The article title, the tags, the author photo — none of it. Just a dark rectangle with my name.

That's a missed opportunity every time someone shares your content. The OG image is the first thing a person sees before they decide whether to click. For a developer writing technical articles to attract clients, "generic image" is not an option.

Next.js App Router has a built-in convention for this: opengraph-image.tsx. The documentation makes it sound straightforward — drop a file in any route segment, get automatic og:image meta tags. The convention works fine in production. In development with Turbopack, however, it hangs the dev server at 300–400% CPU on every first page load and never recovers without a restart.

Here is why it happens, what I use instead, and the things Satori does not tell you up front.

How opengraph-image.tsx Works — And Why It Breaks

The file convention is simple. Create opengraph-image.tsx alongside your page.tsx:

app/
  blog/
    [slug]/
      page.tsx
      opengraph-image.tsx   ← ❌ do not put this here with Turbopack

Enter fullscreen mode Exit fullscreen mode

The file exports a default async function returning an ImageResponse from next/og. Next.js registers a route at /blog/[slug]/opengraph-image and adds the meta tag:

<meta property="og:image" content="https://yoursite.com/blog/my-post/opengraph-image" />

Enter fullscreen mode Exit fullscreen mode

ImageResponse uses Satori under the hood — a library that renders JSX to PNG. You write JSX with inline styles, Satori paints it into an image.

The problem is Turbopack's lazy compilation model.

Turbopack (the default bundler in Next.js 15+) does not compile all routes at startup. It compiles each route segment lazily — the first time you navigate to it in development. That means when you open /blog/some-post for the first time, Turbopack compiles everything in app/blog/[slug]/ together, including opengraph-image.tsx.

next/og bundles Satori, which includes a WebAssembly module for PNG rendering. When Turbopack encounters this WASM for the first time, the Node process in your terminal freezes — CPU climbs to 300–400% on macOS Activity Monitor (or htop on Linux), the browser tab spins indefinitely, and the server never recovers. The only fix is to kill the process and restart. And it happens again on the next slug page you visit.

The symptom has a clear pattern:

  • /blog listing page — loads instantly, CPU stays at 3–5%
  • /blog/some-post — CPU spikes to 300–400%, browser hangs
  • After server restart: same spike on the first visit to any other slug page

If you have searched for "Next.js Turbopack CPU 100%" or "opengraph-image CPU hang" and landed here — this is your problem.

The Correct Approach: API Routes

Turbopack compiles API routes and page routes independently. If you move OG image generation to app/api/og/, Turbopack will compile page.tsx on its own when you navigate to /blog/some-post. Satori's WASM is only compiled when the API route is first hit by an actual HTTP request — which in practice means when a crawler or social preview tool fetches the image, not on every page navigation.

The file structure changes from the broken convention:

app/
  blog/
    [slug]/
      page.tsx
      opengraph-image.tsx   ← compiled with page.tsx, hangs Turbopack

Enter fullscreen mode Exit fullscreen mode

To the correct approach:

app/
  api/
    og/
      blog/
        [slug]/
          route.tsx         ← ✅ compiled independently, Satori runs separately
  blog/
    [slug]/
      page.tsx              ← no opengraph-image.tsx

Enter fullscreen mode Exit fullscreen mode

The generated images are identical — same JSX, same Satori, same PNG output. The only change is the URL path and how Turbopack discovers the code.

The Full Implementation

slug="mvp-development"
text="Building a Next.js SaaS that performs in production is exactly what I ship — auth, infra, perf, OG metadata, all the way to launch."
/>

Here is the complete API route handler for blog post OG images. The design: dark background (#0a0a0f), amber-to-emerald gradient stripe on the left edge, two ambient glow blobs, adaptive title size based on character count, up to four tags as amber chips, and the author section at the bottom.

// app/api/og/blog/[slug]/route.tsx
import { type NextRequest } from "next/server";
import { ImageResponse } from "next/og";
import { readFileSync } from "fs";
import { join } from "path";
import { posts } from "@/.velite";

export const runtime = "nodejs"; // Required for readFileSync

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;
  const post = posts.find((p) => p.slug === slug && !p.draft);

  const title = post?.title ?? "Blog";
  const tags = post?.tags?.slice(0, 4) ?? [];

  // Adaptive font size: shorter titles get larger type
  const titleSize = title.length > 65 ? 42 : title.length > 45 ? 50 : 58;

  // Load author photo from disk — only works with runtime = "nodejs"
  const photoBuffer = readFileSync(join(process.cwd(), "public/images/iurii.png"));
  const photo = `data:image/png;base64,${photoBuffer.toString("base64")}`;

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          backgroundColor: "#0a0a0f",
          position: "relative",
          overflow: "hidden",
        }}
      >
        {/* Ambient glow top-right — amber */}
        <div
          style={{
            position: "absolute",
            top: -120,
            right: -80,
            width: 500,
            height: 500,
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(217,119,6,0.12) 0%, transparent 70%)",
          }}
        />
        {/* Ambient glow bottom-left — emerald */}
        <div
          style={{
            position: "absolute",
            bottom: -100,
            left: 60,
            width: 400,
            height: 400,
            borderRadius: "50%",
            background: "radial-gradient(circle, rgba(5,150,105,0.08) 0%, transparent 70%)",
          }}
        />
        {/* Left accent stripe — amber → emerald */}
        <div
          style={{
            position: "absolute",
            left: 0,
            top: 0,
            width: 5,
            height: "100%",
            background: "linear-gradient(to bottom, #d97706, #059669)",
          }}
        />

        {/* Content layout */}
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            padding: "56px 72px 56px 80px",
            width: "100%",
          }}
        >
          {/* Top: breadcrumb */}
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 17, color: "#6b7280", letterSpacing: "0.03em" }}>
              https://yoursite.com
            </span>
            <span style={{ color: "#374151", fontSize: 17 }}></span>
            <span style={{ fontSize: 17, color: "#6b7280" }}>Blog</span>
          </div>

          {/* Middle: title + tags */}
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 22,
              flex: 1,
              justifyContent: "center",
            }}
          >
            <div
              style={{
                fontSize: titleSize,
                fontWeight: 700,
                color: "#f9fafb",
                lineHeight: 1.2,
                maxWidth: 960,
                letterSpacing: "-0.02em",
              }}
            >
              {title}
            </div>

            {tags.length > 0 && (
              <div style={{ display: "flex", gap: 10 }}>
                {tags.map((tag) => (
                  <div
                    key={tag}
                    style={{
                      fontSize: 15,
                      color: "#d97706",
                      border: "1px solid rgba(217,119,6,0.35)",
                      borderRadius: 20,
                      padding: "4px 14px",
                      backgroundColor: "rgba(217,119,6,0.08)",
                    }}
                  >
                    {tag}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Bottom: author */}
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={photo}
              width={52}
              height={52}
              alt=""
              style={{
                borderRadius: "50%",
                border: "2px solid rgba(217,119,6,0.4)",
                objectFit: "cover",
              }}
            />
            <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
              <span style={{ fontSize: 18, fontWeight: 600, color: "#f9fafb" }}>
                Your Name
              </span>
              <span style={{ fontSize: 15, color: "#6b7280" }}>
                IT Partner for Business · Finland
              </span>
            </div>
          </div>
        </div>
      </div>
    ),
    { width: 1200, height: 630 }
  );
}

Enter fullscreen mode Exit fullscreen mode

A few Satori-specific constraints to be aware of when writing this JSX:

  • Every element that contains children must have display: "flex" set explicitly — block layout does not exist in Satori
  • position: "absolute" works, but you need a parent with position: "relative" and overflow: "hidden" to clip it correctly
  • borderRadius: "50%" works for circles; percentage values on non-square elements may behave differently than in a browser

Gotcha #1: runtime = "nodejs" Is Not Optional

By default, Next.js routes run on the Edge runtime: lightweight, fast, no Node.js APIs. The Edge runtime cannot access the filesystem. If you want to load your author photo from public/images/author.png, you need Node.js.

The readFileSync + base64 pattern is what Satori expects for local images. You cannot use a URL like /images/author.png directly — Satori does not fetch external resources at render time.

If you do not need filesystem access — for example, your image only uses text and inline styles — the Edge runtime works. But the moment you add readFileSync, add export const runtime = "nodejs" above it.

Note that Edge Runtime is also not viable if you load project icons (see Gotcha #3) or any other binary assets from disk.

Gotcha #2: Satori Does Not Support WOFF2

Satori supports TTF and WOFF font formats. WOFF2 — the modern compressed format that every Google Fonts URL defaults to — is not supported.

// This will fail silently or crash the route entirely
const fontResponse = await fetch(
  "https://fonts.gstatic.com/s/inter/v13/UcCO3FwrK3iLTeHuS.woff2"
);
const fontData = await fontResponse.arrayBuffer();

return new ImageResponse(<div>...</div>, {
  fonts: [{ name: "Inter", data: fontData, weight: 400 }],
});

Enter fullscreen mode Exit fullscreen mode

With a WOFF2 URL, the server crashes on the font parsing step. The error message is unhelpful — "Empty reply from server" in some configurations, a silent 500 in others.

The fix is either to use a TTF or WOFF URL, or skip custom fonts entirely. I chose the latter: Satori falls back to Noto Sans, which covers Latin characters cleanly. For OG images, the visual difference is minimal.

If you need a specific typeface, serve TTF from your own domain:

const fontData = await fetch(
  "https://yoursite.com/fonts/Inter-Bold.ttf"
).then((r) => r.arrayBuffer());

return new ImageResponse(<div>...</div>, {
  ...size,
  fonts: [{ name: "Inter", data: fontData, weight: 700, style: "normal" }],
});

Enter fullscreen mode Exit fullscreen mode

Keep the font in public/fonts/ and serve it statically. Avoid Google Fonts CDN — their default URLs return WOFF2.

Gotcha #3: SVG Icons Are Silently Ignored

Satori does not support SVG files in <img> tags. If you load a project icon as a base64 data URI and the file is SVG, Satori will render nothing — no error, no fallback, just an empty space where the icon should be.

The pattern that breaks:

function loadIcon(iconPath: string): string | null {
  try {
    const buffer = readFileSync(join(process.cwd(), "public", iconPath));
    // ❌ Broken for .svg files — Satori ignores SVG image data
    return `data:image/png;base64,${buffer.toString("base64")}`;
  } catch {
    return null;
  }
}

Enter fullscreen mode Exit fullscreen mode

The fix is to rasterize SVG to PNG before passing it to Satori. sharp ships with every Next.js installation:

import sharp from "sharp";

async function loadIcon(iconPath: string): Promise<string | null> {
  try {
    const buffer = readFileSync(join(process.cwd(), "public", iconPath));
    const png = iconPath.endsWith(".svg")
      ? await sharp(buffer)
          .resize(80, 80, { fit: "contain", background: { r: 0, g: 0, b: 0, alpha: 0 } })
          .png()
          .toBuffer()
      : buffer;
    return `data:image/png;base64,${png.toString("base64")}`;
  } catch {
    return null;
  }
}

Enter fullscreen mode Exit fullscreen mode

This handles both PNG and SVG icons transparently. The loadIcon function becomes async, so the call site needs await.

Gotcha #4: Twitter Card Shallow Merge

This one is the least obvious and the most damaging. If you have global metadata in your layout.tsx that includes a static twitter block, and your page.tsx generateMetadata only sets openGraph without an explicit twitter block — Next.js does not automatically connect the two.

The OG image API route will serve the correct dynamic image. The og:image meta tag will point to it. But twitter:image will still reference whatever is in your layout metadata — probably the static og-image.jpeg or nothing. And twitter:title will show your site's global title, not the article title.

This is what the broken state looks like:

URL="https://yoursite.com/blog/some-post"
curl -s "$URL" | grep -E "twitter:|og:"

# og:image correctly points to the API route
<meta property="og:image" content="https://yoursite.com/api/og/blog/some-post" />
<meta property="og:title" content="Article Title | Site Name" />

# twitter:image is still the static fallback from layout
<meta name="twitter:image" content="/og-image.jpeg" />
<meta name="twitter:title" content="Site Name" />   ← site title, not article title

Enter fullscreen mode Exit fullscreen mode

The fix is to explicitly set the twitter block in every generateMetadata function where you want Twitter cards to reflect the page content:

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = posts.find((p) => p.slug === slug);
  if (!post) return {};

  return {
    title: post.seoTitle ?? post.title,
    description: post.summary,
    openGraph: {
      title: `${post.title} | ${siteConfig.name}`,
      description: post.summary,
      type: "article",
      publishedTime: post.date,
      authors: [siteConfig.name],
      tags: post.tags,
    },
    // Without this block, Twitter picks up data from layout.tsx instead
    twitter: {
      card: "summary_large_image",
      title: `${post.title} | ${siteConfig.name}`,
      description: post.summary,
      images: [`${siteConfig.url}/api/og/blog/${slug}`],
    },
  };
}

Enter fullscreen mode Exit fullscreen mode

The images URL in the twitter block needs to be absolute. Next.js does not construct this for you automatically — you have to point it at the route yourself using your site's base URL from config.

After this change, verify with curl:

URL="https://yoursite.com/blog/some-post"
curl -s "$URL" | grep twitter

<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Article Title | Site Name" />
<meta name="twitter:description" content="Article summary..." />
<meta name="twitter:image" content="https://yoursite.com/api/og/blog/some-post" />

Enter fullscreen mode Exit fullscreen mode

You can also paste the URL into Twitter's Card Validator or LinkedIn's Post Inspector to confirm the preview renders correctly.

Reusing the Same Design Across Route Types

The projects route at app/api/og/projects/[slug]/route.tsx is nearly identical to the blog version. The only differences are the breadcrumb label ("Projects" instead of "Blog") and the data source (projects collection instead of posts). Projects also add an optional icon in the top-right corner — handled by the loadIcon function from Gotcha #3.

Rather than duplicating the JSX, you could extract a shared image generator:

// lib/og/generate-card.tsx
import { ImageResponse } from "next/og";
import type { ReactElement } from "react";

interface CardOptions {
  title: string;
  tags: string[];
  breadcrumb: string;
  photo: string; // base64 data URI
  icon?: string | null; // base64 data URI, optional
}

export function buildCardJsx({ title, tags, breadcrumb, photo, icon }: CardOptions): ReactElement {
  const titleSize = title.length > 65 ? 42 : title.length > 45 ? 50 : 58;

  return (
    <div style={{ /* ... same structure as above ... */ }}>
      {/* breadcrumb, title, tags, icon, author */}
    </div>
  );
}

export function generateCard(options: CardOptions) {
  return new ImageResponse(buildCardJsx(options), { width: 1200, height: 630 });
}

Enter fullscreen mode Exit fullscreen mode

I did not bother with this abstraction because the two files are short and independently readable. But if you add a third route type — say, /tags/[tag] — that is when extracting makes sense.

What This Looks Like in Practice

Here is the actual OG image generated for this article — served from /api/og/blog/nextjs-dynamic-og-images:

OG image for this article

After deploying, each blog post and project page generates a unique 1200×630 PNG on demand:

  • Response: HTTP 200, approximately 80–90 KB PNG
  • No build-time pre-rendering — images generate on first request and are cached by the CDN
  • Each blog post and project page has its own preview image
  • Consistent design across all pages: same colors, same typography, same author section

The images are served from the same domain as the rest of the site, which matters for some social platforms that restrict cross-origin OG images.


The opengraph-image.tsx file convention is convenient when it works. But with Turbopack — which is the default since Next.js 15 — it silently kills your dev server on every first page load. The broader production Next.js setup, including metadata and deployment, is covered in my SaaS checklist. Moving generation to app/api/og/ costs you one extra generateMetadata URL, gives you full Node.js APIs, and separates the Satori compilation from your page compilation entirely.

I build production Next.js applications for EU startups and product teams. Projects like vatnode.dev and pikkuna.fi all went through this same setup — correct OG images, proper Twitter cards, full metadata. If you need a senior developer who handles the full stack — from OG metadata to checkout flows — get in touch.

slug="seo-audit"
text="OG images, Twitter cards, and link previews are part of every Technical SEO Audit — alongside schema, sitemap, hreflang, indexing, Core Web Vitals, and per-market keyword research. Fixed fee, written report, 5 working days."
/>


Related reading: