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

推荐订阅源

G
Google Developers Blog
T
Troy Hunt's Blog
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
V
V2EX
I
InfoQ
量子位
Hugging Face - Blog
Hugging Face - Blog
The Register - Security
The Register - Security
J
Java Code Geeks
V
Visual Studio Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security @ Cisco Blogs
爱范儿
爱范儿
Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
Apple Machine Learning Research
Apple Machine Learning Research
V2EX - 技术
V2EX - 技术
罗磊的独立博客
S
Security Affairs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
O
OpenAI News
W
WeLiveSecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
The Hacker News
The Hacker News
Attack and Defense Labs
Attack and Defense Labs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
F
Fortinet All Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
Scott Helme
Scott Helme
B
Blog RSS Feed
有赞技术团队
有赞技术团队
Recent Announcements
Recent Announcements
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
Help Net Security
Help Net Security
NISL@THU
NISL@THU
A
About on SuperTechFans
L
LINUX DO - 最新话题
博客园 - 司徒正美
博客园 - 聂微东
博客园 - 三生石上(FineUI控件)
Spread Privacy
Spread Privacy
P
Proofpoint News Feed

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
Dynamic OG Images in Next.js Without @vercel/og (1,200 630)
Accreditly · 2026-04-27 · via DEV Community

I had a perfectly reasonable OG image template. Flexbox layout, custom font, a gradient background, a small CSS grid for a two-column footer with the author name and publish date. Worked in the browser. Looked great in Figma. Then I moved it into next/og and half of it disappeared.

No errors. No warnings. Satori, the renderer behind ImageResponse, just silently ignored the parts it doesn't support. CSS grid, gone. The calc() I was using for spacing, ignored. A CSS variable for the brand colour, treated as an unknown value. The fallback rendered, which was worse than if it had thrown, because I didn't notice until someone shared the link on Slack and the preview was visibly broken.

If you've been building dynamic OG images in Next.js and hit the same wall, this article is about the other way to do it: rendering your template in an actual browser via an API, and serving the resulting PNG from your opengraph-image route. Same developer ergonomics, no CSS subset to memorise, and your template is literally just HTML and CSS that renders the way you'd expect.

Why @vercel/og falls short once your template gets real

Satori is clever. It parses JSX, approximates a subset of CSS, and produces an SVG which then gets rasterised to PNG. For simple cards, a title over a solid background with one font, it's lovely. The problems show up when your designer hands you something that looks like an actual marketing asset.

Flexbox is supported. Grid is not. display: flex has to be set explicitly on every container, even <span>, because Satori's defaults aren't the browser's. Custom fonts have to be fetched inside the request handler and passed into ImageResponse, not loaded at module scope. The entire bundle, including fonts and any inlined imagery, has to stay under 500KB on Edge. CSS variables don't resolve. calc() doesn't compute. Box shadows work, mostly, until they don't.

You can work around all of this. I did, for a while. The problem is that every design tweak becomes a translation exercise. You're not writing CSS any more, you're writing the subset of CSS that Satori understands, and the feedback loop is slow because rendering happens at request time on Edge.

The alternative that I keep coming back to is rendering the template in a real Chromium instance. You write normal HTML and CSS, including grid, variables, custom fonts loaded with @font-face, animations you can freeze on a specific frame if you want, anything. Then you screenshot it at 1200×630 and serve the PNG. The only question is where that Chromium lives.

Running Puppeteer yourself on Vercel or AWS Lambda is possible but tedious. The chromium binary is too large for the default Lambda size limit, so you end up on @sparticuz/chromium or a layer, watching memory usage, dealing with cold starts, pinning versions when Chrome updates break things. For an OG image pipeline that has to work reliably every time someone shares a link, I'd rather not own that problem. An API that takes HTML and gives you back a PNG cuts out the whole category of infrastructure work.

The approach

The pattern is straightforward. In your route folder, you add an opengraph-image.tsx file (Next.js picks this up automatically and wires it to the right meta tag). Inside it, you build the HTML and CSS for the card using whatever data the route has access to, post it to the html2img API, and return the resulting PNG as the response.

Because Next.js caches OG image routes aggressively by default, you don't pay the API cost on every share. The image gets generated once per unique URL and then served from the framework's cache. If your content changes, you bust the cache the same way you'd bust any route cache.

Building the thing in Next.js

Here's a working implementation for a blog where each post has its own OG image with the title, author, publish date, and category.

Here's what we're going to be making:

Looks great, right?

I'm using the App Router. If you're on Pages Router, the same idea works inside an API route, you just return the bytes yourself.

Inside the post route folder, app/posts/[slug]/opengraph-image.tsx:

import { getPostBySlug } from '@/lib/posts';

export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

export default async function OpengraphImage({
  params,
}: {
  params: { slug: string };
}) {
  const post = await getPostBySlug(params.slug);

  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
          :root {
            --brand: #0b1220;
            --accent: #f59e0b;
            --muted: #94a3b8;
          }
          * { box-sizing: border-box; margin: 0; padding: 0; }
          body {
            width: 1200px;
            height: 630px;
            background: linear-gradient(135deg, var(--brand) 0%, #1e293b 100%);
            font-family: 'Inter', system-ui, sans-serif;
            color: white;
            padding: 80px;
            display: grid;
            grid-template-rows: auto 1fr auto;
          }
          .category {
            font-size: 20px;
            font-weight: 700;
            color: var(--accent);
            text-transform: uppercase;
            letter-spacing: 2px;
          }
          h1 {
            font-size: 68px;
            font-weight: 900;
            line-height: 1.1;
            align-self: center;
            max-width: 900px;
          }
          footer {
            display: grid;
            grid-template-columns: 1fr auto;
            align-items: end;
            color: var(--muted);
            font-size: 22px;
          }
          .author { color: white; font-weight: 700; }
        </style>
      </head>
      <body>
        <div class="category">${escapeHtml(post.category)}</div>
        <h1>${escapeHtml(post.title)}</h1>
        <footer>
          <div><span class="author">${escapeHtml(post.author)}</span> - ${post.publishedAt}</div>
          <div>yourdomain.com</div>
        </footer>
      </body>
    </html>
  `;

  const response = await fetch('https://api.html2img.com/v1/render', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.HTML2IMG_API_KEY}`,
    },
    body: JSON.stringify({
      html,
      viewport_width: 1200,
      viewport_height: 630,
      device_scale_factor: 2,
      wait_for_selector: 'h1',
    }),
  });

  if (!response.ok) {
    throw new Error(`html2img returned ${response.status}`);
  }

  const png = await response.arrayBuffer();

  return new Response(png, {
    headers: {
      'Content-Type': 'image/png',
      'Cache-Control': 'public, max-age=31536000, immutable',
    },
  });
}

function escapeHtml(str: string) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

Enter fullscreen mode Exit fullscreen mode

A few things worth pointing out. device_scale_factor: 2 gives you a retina-quality 2400×1260 PNG, which is what Twitter actually wants these days, rendered into the 1200×630 viewport. wait_for_selector: 'h1' makes sure the page has rendered the heading before the screenshot runs, which matters if you're pulling a font from Google Fonts. Without that wait, you can occasionally get an image where the font hasn't loaded yet and the fallback renders instead.

The escapeHtml helper is not optional. If someone's post title contains a quote character or an ampersand and you interpolate it into an HTML string without escaping, you get either a broken image or, depending on what you're rendering, a small HTML injection vector on your own server. Always escape.

Set your API key as an environment variable and you're done. Next.js will call this function when Twitter or LinkedIn or Slack hits /posts/my-post/opengraph-image.png, cache the result, and serve it from CDN on subsequent requests.

Gotchas I've hit

Fonts are the most common source of surprise. Google Fonts via @import works but adds a network round-trip inside the render. If latency matters to you, either use a system font stack, inline a @font-face with a base64-encoded woff2, or host the font on your own CDN. The wait_for_selector parameter helps, but if the selector appears before the font loads, you still get a fallback. For guaranteed results, add a small ms_delay on top.

Image assets inside the HTML need to be publicly accessible URLs. If your logo is behind auth, inline it as a base64 data URL instead. Same for any background images.

Caching is worth thinking about carefully. The Cache-Control: immutable header on the route is safe because Next.js gives each OG image route a unique URL per slug, but if your post content changes and you want the OG image to reflect that, you need to either include a content hash in the route or manually revalidate. I lean towards including a short hash of the title in the URL for content that might be edited.

Finally, error handling. If the API call fails, you don't want your share previews to break. Wrap the fetch in a try/catch and return a static fallback image on failure. A broken OG image is much worse than a generic one.

The framework-specific setup is covered in more detail in the html2img React and Next.js usage guide. If you want to see more template examples beyond blog cards, the product card and testimonial card examples are good starting points for social-share-style imagery. And for the full list of rendering parameters, including webhook support for async generation when you're batch-regenerating a lot of images, the parameters reference has the complete set.

Write the HTML the way you'd write any landing page, let a real browser render it, cache the output. That's the whole pattern.