This article was translated from Japanese by AI and may contain inaccuracies. For the most accurate content, please refer to the original Japanese version.

There are two main approaches to dynamically generating the OGP (Open Graph Protocol) images that appear when an article or page is shared on social media. The first is to render HTML in a headless browser such as Puppeteer or Playwright and take a screenshot. You get the browser's standard HTML, CSS, and fonts as-is, but managing Chromium binaries, startup costs, and operating it in a serverless environment tend to be a burden. The second is to use a custom layout engine like Vercel's Satori, which converts a subset of HTML and CSS to SVG and then to PNG. It runs fast without a browser, but on edge environments such as Cloudflare Workers, the Worker size bloat from Wasm (WebAssembly) and SVG rasterizers, font handling, and the HTML / CSS restrictions become design challenges.

Void, a Vite-based full-stack toolkit, added void/image, a module for dynamic image generation, in [email protected], released in December 2026. Rather than bundling a custom engine like Satori into the Worker, void/image defaults to handing browser rendering off to local Chromium during development and to Cloudflare Browser Run, Cloudflare's managed execution platform, in production. The design offloads the operational burden of headless browsers to the platform while keeping the Worker lightweight.

How the design came about

In Void's Issue #442, a Satori-based void/og compatible with next/og was originally proposed. The follow-up PR #688 first implemented it with Takumi, a rendering engine written in Rust/Wasm. However, benchmarks showed that bundling the Wasm grew the Worker bundle from about 159 KB (45 KB gzipped) to about 5 MB (2.4 MB gzipped), which also affected responses on routes that don't generate images.

Since OGP images are mainly requested by social media crawlers rather than users, the team decided it made more sense to keep the overall Worker size, CPU time, and memory usage low than to worry about the difference between 50ms and 500ms, and Browser Run became the default. Browser-free renderers such as Takumi can be swapped in with the renderer option.

This article covers the basics of using void/image.

The Basics of OGP Image Generation in Void (void/image)

void/image is a module for returning HTML templates or JSX as PNG images from route handlers. In addition to the general-purpose ImageResponse / renderImage(), it provides OgImageResponse / renderOgImage() with defaults tailored for OGP images.

Creating an Image Route with OgImageResponse

To serve an OGP image for each article, return an OgImageResponse from a dynamic route such as routes/og/[slug].ts. The size defaults to 1200 × 630 pixels, and the response's Content-Type is set to image/png.

routes/og/[slug].ts
import { defineHandler } from "void";
import { html } from "void/html";
import { OgImageResponse } from "void/image";
import { getPost } from "../../src/posts.ts";
 
export const GET = defineHandler(async (c) => {
  const slug = c.req.param("slug");
  const post = slug && (await getPost(slug));
  if (!post) {
    return c.notFound();
  }
 
  return new OgImageResponse(
    html`<article style="height: 100%; padding: 80px; background: #0f172a; color: white">
      <h1 style="font-size: 72px">${post.title}</h1>
      <p style="font-size: 36px">${post.author}</p>
    </article>`,
  );
});

The key point is that the markup uses void/html (a re-export of Hono's html helper) rather than a plain string. void/image rejects plain strings by throwing a TypeError. With the html tag or Hono JSX (covered later), embedded values such as ${post.title} are HTML-escaped by default, preventing unintended tag injection and external image requests.

To change the size, pass width and height in the second argument.

return new OgImageResponse(content, {
  width: 600,
  height: 600,
});

Setting og:image in the Page's <head>

To link the image route to each page, use defineHead() in a Pages-mode .server.ts file to return the meta tags.

pages/posts/[slug].server.ts
import { defineHead } from "void";
 
interface Props {
  post: { title: string; slug: string; description: string; author: string };
}
 
export const head = defineHead<Props>((c, { post }) => ({
  title: post.title,
  meta: [
    { property: "og:type", content: "article" },
    { property: "og:title", content: post.title },
    { property: "og:description", content: post.description },
    { property: "og:url", content: c.req.url },
    { property: "og:image", content: `/og/${encodeURIComponent(post.slug)}` },
    { property: "og:image:width", content: "1200" },
    { property: "og:image:height", content: "630" },
    { property: "og:image:alt", content: `${post.title} by ${post.author}` },
    { name: "twitter:card", content: "summary_large_image" },
  ],
}));

On pages rendered at request time, you can write a relative path such as /og/... in og:image or twitter:image, and Void expands it to an absolute URL using the request's origin. However, prerendered pages generated at build time have no request, so you need to specify the full URL directly, such as https://example.com/og/.... Also, the OGP image route must be accessible without logging in so that social media crawlers can fetch it without authentication.

Writing Templates in Hono JSX

Adding /** @jsxImportSource void/jsx */ at the top of the file lets you write templates in Hono JSX (for TypeScript type checking, you need to enable "jsx": "react-jsx" in tsconfig.json). Note that the JSX is written directly, without the html tag function.

routes/og/[slug].tsx
/** @jsxImportSource void/jsx */
import { defineHandler } from "void";
import { OgImageResponse } from "void/image";
import { getPost } from "../../src/posts.ts";
 
export const GET = defineHandler(async (c) => {
  const slug = c.req.param("slug");
  const post = slug ? await getPost(slug) : undefined;
  if (!post) {
    return c.notFound();
  }
 
  return new OgImageResponse(
    <article
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        height: "100%",
        padding: "72px",
        background: "#0f172a",
        color: "#f8fafc",
      }}
    >
      <h1 style={{ margin: 0, fontSize: "64px", lineHeight: 1.3 }}>{post.title}</h1>
      <p style={{ margin: 0, fontSize: "30px", color: "#94a3b8" }}>@{post.author}</p>
    </article>,
  );
});

As with void/html, embedded values in JSX (such as {post.title}) are escaped by default.

Rendering Up Front with renderOgImage()

OgImageResponse and renderOgImage() differ in when they run. OgImageResponse is a subclass of Response and internally uses a ReadableStream body to defer rendering until the handler returns the response and the body is read. As a result, you cannot catch a rendering failure with try / catch inside the handler and swap in a different response.

If you want to return a fallback when rendering fails, or save the generated PNG bytes to storage such as R2, await renderOgImage(). The following code wraps renderOgImage() in try / catch and returns a 503 on failure.

routes/og-jsx/[slug].tsx
/** @jsxImportSource void/jsx */
import { defineHandler } from "void";
import { renderOgImage } from "void/image";
import { getPost } from "../../src/posts.ts";
 
export const GET = defineHandler(async (c) => {
  const slug = c.req.param("slug");
  const post = slug ? getPost(slug) : undefined;
  if (!post) {
    return c.notFound();
  }
 
  try {
    const png = await renderOgImage(
      <article
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          height: "100%",
          padding: "72px",
          background: "#0f172a",
          color: "#f8fafc",
        }}
      >
        <h1 style={{ margin: 0, fontSize: "64px", lineHeight: 1.3 }}>{post.title}</h1>
        <p style={{ margin: 0, fontSize: "30px", color: "#94a3b8" }}>@{post.author}</p>
      </article>,
      {
        lang: "ja",
        font: ["Noto Sans CJK JP", "Roboto", "Noto Color Emoji", "sans-serif"],
      },
    );
 
    return new Response(png, {
      headers: {
        "content-type": "image/png",
        "cache-control": "public, max-age=86400",
      },
    });
  } catch (error) {
    console.error("OGP image render failed:", error);
    return c.text("Failed to render image", 503);
  }
});

renderOgImage() returns Promise<Uint8Array<ArrayBuffer>>. Because it waits for rendering to finish before any headers are sent, you can control the fallback on failure. On the other hand, since it is an API that returns raw bytes, you need to set content-type and cache-control yourself when building the Response.

Caching Behavior

OgImageResponse automatically sets Cache-Control: public, max-age=86400 (24 hours) only when both of the following conditions are met:

  • It is running somewhere other than the dev server (an environment where import.meta.env.DEV is not true)
  • You have not specified cache-control in the headers option

In other words, the header is not added on the npm run dev dev server, and if you specify cache-control yourself, your value is used as-is. To change the cache duration, specify it in headers like this:

return new OgImageResponse(content, {
  headers: { "cache-control": "public, max-age=3600" },
});

To cache images at the edge so that repeated requests to the same URL don't trigger browser rendering every time, use routing.revalidate in void.config.ts. If you vary the image by query parameters, list the parameter names in routing.revalidateQueryAllowlist (in the form { "/og/*": ["param"] }).

void.config.ts
import { defineConfig } from "void/config";
 
export default defineConfig({
  routing: {
    revalidate: { "/og/*": 86400 },
  },
});

Note, however, that social media crawlers may cache images longer than max-age, so shortening the cache duration does not guarantee that changes show up immediately. To reflect a change without waiting for caches to expire, you need to change the image URL itself and update og:image.

Note

As of December 2026, Browser Run is available on the Workers Free plan, but browser time is limited to 10 minutes per day and Quick Actions requests to one every 10 seconds. The Workers Paid plan includes 10 hours per month, with additional usage billed at $0.09 per hour. Quick Actions requests are limited to 30 per second. Exceeding these limits returns HTTP 429, and image generation fails. Cache images with routing.revalidate so the same image isn't rendered over and over, and use renderOgImage() as described above if you want to return a different response on failure. Check Limits and Pricing for the latest limits and pricing.

Running It Locally and in Production on Cloudflare

From here, we'll create a minimal Void app and generate OGP images both locally (Chromium on macOS) and in production on Cloudflare Workers (Browser Run) to see how it behaves.

Project Configuration and compatibility_date

To use Browser Run Quick Actions from a Worker binding, the Worker's compatibility_date must be 2026-03-24 or later. If an existing Void project pins an older date, update it in void.config.ts.

void.config.ts
import { defineConfig } from "void/config";
 
export default defineConfig({
  worker: {
    compatibility_date: "2026-03-24",
  },
});

vite.config.ts is a minimal setup that only registers voidPlugin().

vite.config.ts
import { defineConfig } from "vite";
import { voidPlugin } from "void";
 
export default defineConfig({
  plugins: [voidPlugin()],
});

Implementing the OGP Route

Define some test articles in src/posts.ts, and make article data available through getPost(). The titles are left in Japanese to check how Japanese text and emoji are rendered.

src/posts.ts
export interface Post {
  slug: string;
  title: string;
  author: string;
  category: string;
  publishedAt: string;
}
 
const posts: Record<string, Post> = {
  "void-ogp": {
    slug: "void-ogp",
    title: "Void の OGP 画像生成と Satori との違い",
    author: "azukiazusa",
    category: "WEB DEVELOPMENT",
    publishedAt: "2026-12-05",
  },
  "browser-run": {
    slug: "browser-run",
    title: "Cloudflare Browser Run で HTML から PNG を生成する 🖼️",
    author: "azukiazusa",
    category: "CLOUDFLARE",
    publishedAt: "2026-12-05",
  },
};
 
export function getPost(slug: string): Post | undefined {
  return posts[slug];
}

Next, create routes/og/[slug].ts. In addition to CSS Grid and linear-gradient, it places a vertical label using writing-mode: vertical-rl and specifies the preinstalled Noto Sans CJK JP and Noto Color Emoji fonts. Since it renders in a real browser, the advantage is that there are no CSS restrictions.

routes/og/[slug].ts
import { defineHandler } from "void";
import { html } from "void/html";
import { OgImageResponse } from "void/image";
import { getPost } from "../../src/posts.ts";
 
export const GET = defineHandler((c) => {
  const slug = c.req.param("slug");
  const post = slug ? getPost(slug) : undefined;
  if (!post) {
    return c.notFound();
  }
 
  return new OgImageResponse(
    html`<style>
        .card {
          display: grid;
          grid-template-columns: 1fr auto;
          height: 100%;
          padding: 64px 72px;
          background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
          color: #f8fafc;
        }
        .main {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding-right: 48px;
        }
        .title {
          margin: 0;
          font-size: 62px;
          line-height: 1.3;
          font-weight: 700;
        }
        .meta {
          display: flex;
          gap: 24px;
          font-size: 28px;
          color: #94a3b8;
        }
        .side {
          writing-mode: vertical-rl;
          border-left: 2px solid #334155;
          padding-left: 32px;
          font-size: 24px;
          letter-spacing: 0.2em;
          color: #38bdf8;
        }
      </style>
      <article class="card">
        <div class="main">
          <h1 class="title">${post.title}</h1>
          <div class="meta">
            <span>@${post.author}</span>
            <span>${post.publishedAt}</span>
          </div>
        </div>
        <aside class="side">${post.category}</aside>
      </article>`,
    {
      lang: "ja",
      font: ["Noto Sans CJK JP", "Roboto", "Noto Color Emoji", "sans-serif"],
    },
  );
});

Checking the Build Output and Resource Inference

Building this project (including routes/og-jsx/[slug].tsx from earlier) produced 11 chunks totaling about 112 kB (about 42 kB gzipped). The main chunks are shown below.

# ... (other small chunks omitted)
.cloudflare/output/v1/workers/default/bundle/assets/browser-run-DoPvyKwY-cfeBuev9.js   4.94 kB │ gzip:  2.45 kB
.cloudflare/output/v1/workers/default/bundle/assets/image-vvPlXgMR.js                 35.09 kB │ gzip: 12.52 kB
.cloudflare/output/v1/workers/default/bundle/index.js                                 49.82 kB │ gzip: 17.39 kB
✓ built in 47ms

Looking at the key fields in the generated .cloudflare/output/v1/workers/default/worker.config.json, a BROWSER binding had been added to env automatically, even though I hadn't written a wrangler.jsonc at all.

worker.config.json
{
  "name": "void-ogp-image-generation",
  "compatibilityDate": "2026-03-24",
  "env": {
    "BROWSER": { "type": "browser" },
    "ASSETS": { "type": "assets" }
  }
}

Behavior on the Local Dev Server

Start the dev server with npm run dev and open /og/void-ogp, and you get back a PNG image like the one below.

Locally, Miniflare emulates Browser Run and automatically downloads a Chromium build for local use (chrome-headless-shell) the first time an image is generated. Because of this, the first request doesn't respond until the download finishes, so it takes a while. Subsequent requests use the already-downloaded Chromium.

Checking the headers returned by OgImageResponse in the development environment shows that content-type: image/png and transfer-encoding: chunked are set automatically. Note that cache-control is not added on the local dev server.

Deploying to Cloudflare and Testing with Browser Run

Running npx void deploy --platform cloudflare deploys straight to Cloudflare Workers. In production, I confirmed that cache-control: public, max-age=86400 was added automatically.

You can see that the OGP image is generated as expected.

A 1200 × 630 OGP image generated by Cloudflare Browser Run, with Japanese text, an emoji, and a vertical label

Checking the Browser Run logs in the Cloudflare dashboard shows that a Screenshot action was executed.

Summary

  • void/image, added in Void 1.13, doesn't bundle a custom layout engine like Satori into the Worker. Instead, it offloads rendering to local Chromium during development and to Cloudflare Browser Run in production
  • Simply importing void/image causes the BROWSER binding to be inferred automatically
  • OgImageResponse lazily renders a 1200 × 630 PNG and, outside the dev server, adds Cache-Control: public, max-age=86400 unless you specify cache-control yourself. When you need fallback handling on failure or want to store the bytes, await renderOgImage()

References

Comprehension check

Answer the following questions to deepen your understanding of the article.

According to the article, when should you `await` `renderOgImage()` instead of using `OgImageResponse`?

  • When you want `Cache-Control: public, max-age=86400` to be added automatically in production

    Try again

    `OgImageResponse` is the one that adds the 24-hour cache header automatically in production. `renderOgImage()` returns raw PNG bytes, so you set the headers yourself.

  • When you want to generate an image at a size other than `1200 × 630` (such as a square thumbnail)

    Try again

    `OgImageResponse` also accepts a size in its second argument, such as `{ width: 600, height: 600 }`.

  • When you want to return a fallback from a `try / catch` in the handler if rendering fails, or save the generated PNG bytes to storage

    Correct!

    As the article explains, `OgImageResponse` defers rendering until the body is read, so the handler cannot catch rendering failures. To render up front and handle errors or save the image to R2, `await` `renderOgImage()`.

  • When you want to write the template in Hono JSX (`void/jsx`) instead of `void/html`

    Try again

    Hono JSX works with both `OgImageResponse` and `renderOgImage()`.