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

推荐订阅源

V
Visual Studio Blog
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
T
The Exploit Database - CXSecurity.com
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
月光博客
月光博客
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
NISL@THU
NISL@THU
爱范儿
爱范儿
S
Securelist
博客园 - 叶小钗
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
D
DataBreaches.Net
G
GRAHAM CLULEY
P
Proofpoint News Feed
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
Jina AI
Jina AI
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
博客园 - 【当耐特】
H
Help Net Security
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss

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
What I learned generating OG images for articles with Playwright and zero API cost
MORINAGA · 2026-05-15 · via DEV Community

The conclusion first: for a batch of under a few hundred static articles, generating OG images by screenshotting HTML templates with Playwright costs nothing, gives you full CSS control, and requires zero external API keys. The trade-offs are real — it's slow per image, it's not suitable for on-demand generation, and it has a hidden dependency on network availability during the build step. But for my use case, those trade-offs don't hurt.

Here's how the script works, what broke, and what I'd do differently.

Why I avoided image generation APIs

My three directory sites — aiappdex.com, findindiegame.com, ossfind.com — are fully static Astro 5 SSG builds. Articles publish automatically through a GitHub Actions pipeline. The pipeline already handles Dev.to, Hashnode, and Bluesky distribution, plus YouTube thumbnail generation with ffmpeg. I didn't want to add a billed API dependency to this stack.

The options I considered:

  • Cloudinary with remote transformations: works for on-demand, but requires a paid plan for custom fonts and the transformation URL syntax is brittle to URL-encode correctly.
  • @vercel/og (Satori-based): excellent for Next.js and Vercel serverless functions, but my sites are static pages on Cloudflare Pages — there's no Edge runtime to serve dynamic OG images from.
  • node-canvas: full control, zero cost, but native C++ binding compilation in GitHub Actions runners is a recurring pain point. It works, but it adds a non-trivial setup step to CI.
  • Pillow (Python image library): draws to a bitmap directly. Fine for simple layouts, but anything involving custom fonts, gradients, or CSS flexbox behavior is either impossible or requires dozens of manual coordinate calculations.

The Playwright approach: build an HTML string with CSS, pass it to a headless browser, screenshot it. The browser handles fonts, gradients, flexbox, and every other CSS feature I want to use. No API key. No external service. Just a 160-line Python script and Playwright installed in the runner.

How the HTML template and accent color system works

The script builds a full HTML document as a string, fills in the article title, date, and tags, and hands it to Playwright. The template has a dark card layout with an Inter typeface loaded from Google Fonts CDN.

The one non-obvious piece is the accent color selection. Each article has tags like ["webdev", "astro", "tutorial", "githubactions"]. The script matches these against five regex rules to pick an accent color:

ACCENT_RULES: list[tuple[str, str]] = [
    (r"\b(claude|anthropic|ai|llm|machinelearning)\b", "#8B5CF6"),  # purple
    (r"\b(astro|webdev|tailwindcss|react|nextjs|typescript|javascript)\b", "#0EA5E9"),  # blue
    (r"\b(godot|gamedev|csharp|game|unity)\b", "#22C55E"),  # green
    (r"\b(opensource|github|programming|tutorial)\b", "#F97316"),  # orange
    (r"\b(showdev|indiehackers|productivity)\b", "#F59E0B"),  # amber
]
DEFAULT_ACCENT = "#475569"  # slate fallback

Enter fullscreen mode Exit fullscreen mode

Rules are checked in order; the first match wins. An article tagged ["ai", "webdev"] would pick purple, because ai matches the first rule before webdev matches the second.

The accent color is inserted into the HTML at three points: the background radial gradient (at two different opacity levels: accent + "55" and accent + "33"), the brand mark block, and the tag pill borders. This gives each article a visually distinct color family without requiring any per-article design decision.

Font size also adjusts dynamically: titles over 70 characters render at 54px; shorter titles render at 64px. This is a heuristic that prevents long titles from overflowing the card boundary. It's not perfect for every title, but I haven't needed to manually override anything across 22 articles yet.

The key implementation: wait_until="networkidle"

The core Playwright call is:

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(viewport={"width": 1200, "height": 630})
    page = context.new_page()

    page.set_content(html, wait_until="networkidle")
    page.screenshot(
        path=str(out_path),
        full_page=False,
        clip={"x": 0, "y": 0, "width": 1200, "height": 630}
    )

Enter fullscreen mode Exit fullscreen mode

The wait_until="networkidle" argument was the critical discovery. Without it, Playwright fires the screenshot as soon as the DOM is ready — before Google Fonts has loaded and applied Inter. The result: the fallback system-ui font renders instead, which looks noticeably different and varies by the runner's OS default.

networkidle tells Playwright to wait until there are no more than 0 network connections for 500ms. In practice this means the Google Fonts CDN request completes and Inter loads before the screenshot fires. This adds roughly 300–500ms per image.

The template includes <link rel="preconnect" href="https://fonts.googleapis.com"> and the corresponding gstatic.com preconnect to minimize the latency. Without preconnect, I saw occasional timeouts where the font didn't load fast enough within the idle window.

The browser instance stays open across all articles

One implementation detail that matters for batch performance: the script opens a single browser instance and reuses the same page object across all articles, calling set_content() in a loop rather than navigating to a URL.

This is faster than opening a new browser per article because Playwright browser startup time is around 500ms. For 22 articles, that's ~11 seconds saved. For 200 articles, it would be ~100 seconds.

The clip parameter on screenshot() is necessary even though the viewport is already set to 1200x630. Without it, Playwright screenshots include a 1px bottom border artifact on some versions of Chromium. The clip forces the exact pixel region I want.

Two image formats from one pipeline

The same GitHub Actions job runs two separate scripts: generate-og.py for the standard 1200×630 OG image (used by Twitter/X, LinkedIn, Dev.to article cards), and generate-summary.py for a 1080×1350 portrait image optimized for Bluesky's visual post format.

The portrait image uses a structured layout with optional sections — card grids, pipeline diagrams, or stat blocks — depending on what summary_data YAML is present in the article frontmatter. Articles that don't have summary_data skip the portrait generation entirely and fall back to the URL card Bluesky generates natively.

This is the same pipeline that runs the post-deploy JSON-LD audit and Bluesky image upload. Adding image generation was a matter of adding two python3 scripts/... steps — no new runner setup beyond pip install playwright && playwright install chromium.

The cover_image auto-patch

One quality-of-life feature: the script writes cover_image: <url> back into the article's frontmatter automatically if it's missing.

def update_cover_image(article_path: Path, slug_base: str) -> bool:
    content = article_path.read_text(encoding="utf-8")
    meta, _ = parse_frontmatter(content)
    if meta.get("cover_image"):
        return False
    cover_url = f"{HOST}/og/articles/{slug_base}.png"
    new_content = re.sub(
        r"^(---\n)([\s\S]*?)(\n---\n)",
        lambda m: m.group(1) + m.group(2) + f"\ncover_image: {cover_url}" + m.group(3),
        content, count=1,
    )
    article_path.write_text(new_content, encoding="utf-8")
    return True

Enter fullscreen mode Exit fullscreen mode

The URL is deterministic — it's the slug plus .png on my CDN. The script generates the image first, then updates the frontmatter. Dev.to and Hashnode both read cover_image from the frontmatter when publishing, so the OG image shows up as the article cover automatically. No manual step.

Comparison: Playwright vs the alternatives

Approach API cost CSS control CI-friendly On-demand capable Font flexibility
Playwright + HTML $0 Full Yes (slow, ~2s/image) No Any web font
Cloudinary transformations $89/mo at scale Template only Yes Yes Cloudinary library
@vercel/og (Satori) $0 JSX subset Vercel only Yes Web fonts via fetch
node-canvas $0 Full Needs native build Yes System + manual
Pillow + Python $0 Pixel-level only Yes Yes PIL-loaded fonts

For static sites where every page is a flat HTML file, on-demand OG generation is irrelevant — there's no server to serve it from. Playwright is the only option on this list that gives full CSS control without either native compilation issues or a billed external service.

What I'd change

Bundle Inter locally instead of fetching from Google Fonts. The networkidle approach works, but it means a slow or blocked CDN during CI can cause font loading failures. Bunding the Inter woff2 file in the repo eliminates the network dependency entirely. I haven't done this yet because Google Fonts is convenient and the CDN has been reliable, but a CI failure at 07:00 JST because of a Google CDN blip would motivate the change immediately.

Run images in parallel with asyncio. The synchronous Playwright API processes articles sequentially. For 22 articles at ~2 seconds each, total time is around 45 seconds. For 200 articles, it would be ~7 minutes — too slow for a per-commit CI step. The async Playwright API supports asyncio.gather() for concurrent page instances. I'll need this before the article count gets much larger.

One Playwright instance per image format. Currently generate-og.py and generate-summary.py are separate scripts that each launch their own browser. A single script that generates both formats per article would halve browser launch overhead. Minor at current scale, relevant at 200+ articles.

The hard limit: not suitable for on-demand generation

If you need OG images generated per-request — for a blog where new posts are published dynamically, or for a user-facing tool — this approach doesn't work. Playwright takes 2+ seconds per image and requires a full Chromium binary. Serving that from a request path is impractical.

For on-demand generation at low volume, @vercel/og or a Cloudflare Worker with a canvas API is the right answer. For batch generation at build time in CI, where you control the timing and don't care about per-image latency, Playwright is simpler than any alternative I've found.

FAQ

Q: Why Python instead of Node.js Playwright?

Both Playwright SDKs are functionally equivalent for this use case. I chose Python because my other image-related scripts (generate-summary.py, polish.py) were already Python, and keeping them in one language simplifies the CI setup. The sync_playwright API is slightly more readable than the async Node.js version for sequential batch processing.

Q: Does wait_until="networkidle" always ensure fonts load?

Not guaranteed. networkidle fires when there are zero network connections for 500ms. If the Google Fonts CDN request hasn't started yet when the idle window begins — which can happen if Playwright is very fast at rendering the DOM — the font request comes after the screenshot. In practice, the <link rel="preconnect"> tags I added push the font request early enough that I haven't seen this failure mode. A more reliable approach is to wait for a specific CSS font to be applied using page.wait_for_function("document.fonts.ready").

Q: Can I use this for dynamically generated pages?

Yes, with caveats. You can pass a real URL instead of set_content() using page.goto(url, wait_until="networkidle"). This works well for screenshotting pages that already exist. The timing is less predictable than screenshotting a controlled HTML string because you don't control what JavaScript the page runs.

Q: Why not use Satori directly without @vercel/og?

Satori is an interesting option — it renders JSX to SVG, which you can then convert to PNG with sharp. It's faster per image than Playwright, doesn't require a browser binary, and works in any Node.js environment. The limitation is that it supports a subset of CSS: no background-image: radial-gradient(), no backdrop-filter, limited position support. For my template — which depends on radial gradients for the card background — Satori would require redesigning the layout.

Q: How does the cover image URL work if the PNG isn't published yet?

The cover_image URL points to https://aiappdex.com/og/articles/<slug>.png. The script generates the PNG first and commits it to the repository. Cloudflare Pages deploys the committed file, so by the time the article publishes to Dev.to and Hashnode, the OG image is already live at that URL. The sequence matters: image generation and commit happen before the publish step runs.

Related reading:

Part of an ongoing 6-month experiment running three AI-curated directory sites. The technical claims here are real; this article was AI-assisted.