Skip to content

feat(void): add ImageResponse for Open Graph images in void/og - #688

Open
ogawa0071 wants to merge 52 commits into
voidzero-dev:mainfrom
ogawa0071:feat/og-image
Open

ogawa0071 wants to merge 52 commits into
voidzero-dev:mainfrom
ogawa0071:feat/og-image

Conversation

@ogawa0071

@ogawa0071 ogawa0071 commented Nov 3, 2026 •

Copy link
Copy Markdown

Closes #442

Summary

Adds void/og: an ImageResponse that renders JSX or an HTML string to a PNG from a route handler, for Open Graph and social preview images, on Cloudflare Workers and on the Node.js, Bun and Deno targets.

// routes/og/[slug].tsx
import { defineHandler } from 'void';
import { ImageResponse } from 'void/og';

export const GET = defineHandler((c) =>
  new ImageResponse(
    <div style={{ display: 'flex', fontSize: 72 }}>Hello {c.req.param('slug')}</div>,
  ),
);

Options

ImageResponseOptions is Void's own list, mapped to Takumi's render options one by one, so a Takumi upgrade does not change the API:

  • width, height, debug, fonts, emoji (twemoji, blobmoji, noto, openmoji, fluent, fluentFlat), status, statusText, headers.
  • lang: chooses the style of Chinese characters, as the root element's lang attribute does.
  • images: allowUrl, maxBytes, timeout and throwOnError for the images and emoji in the markup. allowUrl is how an app keeps request values in image URLs from reaching internal addresses on the Node.js target.
  • A fonts entry is { name, data, weight?, style?, lang? } with the font's bytes, or a font file's URL. weight is any number from 1 to 1000; leaving it out lets a variable font follow each element's fontWeight.
  • fallbackFonts: false turns off the Google Fonts downloads described below, for apps that pass their own fonts.

Takumi's other options (format, devicePixelRatio, css, renderer, module and so on) are not accepted.

Why Takumi

Takumi (takumi-js) ships a Wasm build with a workerd export condition, which the Cloudflare Vite plugin loads as a compiled module in dev and builds, plus a native addon for Node.js and Bun. It takes JSX or HTML and draws straight to pixels, so void/og stays a thin wrapper.

Warm render times for 1200 × 630 cards in workerd (Miniflare, median):

Card Takumi Wasm
Title and author 10 ms
Gradient, shadow, tags 31 ms
~1,300 characters of text 13 ms

The first request in a new isolate takes about 110 ms. With the native addon on Node.js, the same cards take 3–10 ms.

What the wrapper adds

  • Defaults: a 1200 × 630 PNG, Content-Type, and debug. Cache-Control is public, max-age=0, must-revalidate. The guide shows how to cache image routes with routing.revalidate.
  • Fallback fonts: Takumi's built-in Geist covers Latin, so for text it cannot draw (Japanese, Chinese, Korean, Thai, Arabic, Cyrillic, symbols and more) the wrapper loads the matching Noto family, or Geist's own Latin Extended and Cyrillic subsets, from Google Fonts.
    • Each family is requested with text= and only the characters the image uses, so Google returns one small file. On a deployed Worker, a 45-character Japanese title takes 2 requests and a 26 KB file, against 21 requests and 480 KB for the per-range files. Text too long for one request (about 650 CJK characters) falls back to the per-range files.
    • A server keeps each downloaded font until it restarts, about 37 KB per new title in a Node.js test of 800 titles. The guide describes this, and fallbackFonts: false with the app's own fonts avoids it.
    • Han text is drawn as Japanese unless lang names the language or the text has Hangul. An explicit lang wins over kana, so a Traditional Chinese title with a katakana word stays Chinese.
    • Variable families are requested with their full weight range, so fontWeight: 700 draws real bold rather than a thickened regular.
    • Latin text stays on the built-in Geist. A fallback file that fails to download is left out on its own; the others still render.
  • Font handling lives in packages/void/src/runtime/og-fonts.ts.
  • Each image renders with only its own fonts (Takumi otherwise uses every font registered in the process), fonts passed as bytes register once, and emoji images are cached per isolate.

Node.js, Bun and Deno

Takumi loads its renderer from files next to its own code, which a bundle cannot carry. On these targets the build fails with the install command when the app has no supported takumi-js in its own dependencies; the dev server only warns.

The app installs takumi-js because the production install runs on the server, so it fetches the native binary for that OS and CPU. Two alternatives were considered and left out:

  • Rendering with Takumi's Wasm build on Node.js needs no install and gives identical PNGs, but renders 2.5–3× slower (a rich card: 20 ms against 6.5 ms) and uses about 70 MB more memory.
  • Copying takumi-js and the build machine's binary into dist/ssr adds about 12 MB and breaks when the build runs on another platform than the server, such as macOS to a Linux container.

The build accepts any takumi-js in Void's ~2.20.0 range, so raising that range later asks Node.js apps to update theirs.

Workers Free

Apps that don't import void/og bundle nothing extra (covered by a test). Takumi's Wasm adds about 4.3 MB (1.9 MB gzipped) to the Worker. A simple card takes around 10 ms of CPU, richer ones 30–80 ms, and the first render in a new isolate more than 100 ms, so the guide tells Workers Free apps to cache image routes with revalidation.

takumi-js version

takumi-js is on ~2.20.0. 2.19.0 loads only the first font whose unicode-range covers a character and draws the whole word as .notdef boxes when that font lacks the glyph: with Japanese in the image, "Łódź" renders as boxes. 2.20.0 fixes this: Japanese next to Polish, symbols, mixed scripts, bold Japanese and twemoji render pixel-identical to 2.18.2 with both the native and Wasm backends, and the built-in Geist draws the same code points. The build rejects 2.19.x. packages/void/AGENTS.md notes how to check a version before raising the range.

Docs

  • New guide: docs/guide/og-images.md, with options, fonts, controlling font downloads, caching, Worker size, and the Node.js, Bun and Deno setup.
  • void/og in the API reference, a link from the head() guide, a note in the Node.js, Bun and Deno integration guide, and a task row in the void skill.

Tests

  • packages/void/test/unit/og.test.ts (34 tests): defaults and headers, JSX, font weights, options outside ImageResponseOptions not reaching Takumi, fallback-font selection and text= requests (including Han text next to Hangul), the long-text fallback, fallbackFonts: false, weights and subsetting, lang, per-image font isolation, partial fallback download failures, emoji, images.throwOnError, and the Node.js build check.
  • packages/void/test/integration/og-image.test.ts (6 tests): the dev server in workerd, the built Worker in Miniflare (one CompiledWasm module), an app without React, an app without void/og (no Wasm in its bundle), and the Node.js target, which renders with the app's takumi-js and fails the build without it.
  • .github/scripts/packed-consumer.mjs renders an image route from the packed tarballs in dev and preview, and on the Node.js target.

🤖 Generated with Claude Code

@ogawa0071
ogawa0071 requested a review from a team as a code owner November 3, 2026 14:44
@socket-security

socket-security Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedtakumi-js@​2.20.01001009696100

View full report

@yangshun yangshun self-assigned this Nov 11, 2026
@yangshun yangshun changed the title feat(void): add next/og-compatible ImageResponse in void/og feat(void): add ImageResponse for Open Graph images in void/og Nov 12, 2026
Comment thread docs/guide/og-images.md Outdated
Comment on lines +180 to +182
## Worker size

On Cloudflare, importing `void/og` adds Takumi's WebAssembly renderer to your Worker: about 4.3 MB, or 1.9 MB compressed. Cloudflare limits a Worker to 3 MB compressed on Workers Free and 10 MB on Workers Paid (see [Worker size](https://developers.cloudflare.com/workers/platform/limits/#worker-size)), so on Workers Free the rest of your app has about 1.1 MB. Apps that do not import `void/og` do not include the renderer.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cloudflare changed these limits on September 4, 2026: the 3 MB (Free) and 10 MB (Paid) check on the compressed bundle was removed, and Workers Free and Workers Paid now both allow 64 MiB, measured uncompressed (changelog, Worker size). The limits page now says: “There is no compressed size limit. Only the uncompressed bundle size counts.”
So void/og adds about 4 MiB, which fits on either plan with plenty of room.

@yangshun yangshun Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the tip. I forgot about that and am glad they're much higher now. I'm glad the size concern is gone. Will update it!

@yangshun yangshun left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ogawa0071 Thanks for the PR! I've pushed some follow-up commits on top of yours. Summary below, please have a look and lemme know if there's anything amiss.

At the bottom there are notes for reviewers (cc @cpojer):

Changes since the original submission

API

  • ImageResponseOptions is now Void's own list, mapped to Takumi's options one by one: width, height, debug, fonts, fallbackFonts, emoji, lang, images (allowUrl, maxBytes, timeout, throwOnError), plus status, statusText and headers. Takumi's other options (format, devicePixelRatio, css, renderer, module, fontFamilies, …) are no longer accepted, so a Takumi upgrade can't change Void's API, and backend options can't bypass the per-image font handling.
  • A fonts entry is a font file's URL or { name, data, weight?, style?, lang? }. weight accepts any value from 1 to 1000; leaving it out lets a variable font follow each element's fontWeight (e.g. 550).
  • New fallbackFonts: false turns off the Google Fonts downloads, for apps that pass their own fonts.
  • Cache-Control is always public, max-age=0, must-revalidate. The dev-only no-cache, no-store was dropped: with max-age=0 and no validator, clients refetch anyway.

Fallback fonts

  • Fonts are requested from Google Fonts with text= and only the characters in the image, so Google returns one small file. On a deployed Worker, a 45-character Japanese title went from 21 requests / 480 KB to 2 requests / 26 KB. Text too long for one request falls back to the per-range files.
  • An explicit lang now chooses the Chinese, Japanese or Korean style before kana or Hangul in the text, so a Traditional Chinese title with a katakana word stays Chinese.
  • ・ and ー are drawn with the Japanese family rather than a separate request.
  • Han text next to Hangul is drawn: both scripts went to Noto Sans KR, and the Hangul request replaced the Han one, so mixed Chinese/Japanese/Korean text drew boxes.
  • Variable families are requested with their full weight range, so fontWeight: 700 draws real bold rather than a thickened 400.
  • When one fallback file fails to download, only that file is dropped; the others still render.
  • Font handling moved into packages/void/src/runtime/og-fonts.ts.

Dependencies and build

  • Upgraded to takumi-js ~2.20.0, which fixes 2.19.0's fallback regression ("Łódź" next to Japanese drew as boxes). 2.20.0 renders pixel-identical to 2.18.2 on both backends.
  • The Node.js build check finds void's package.json without assuming the module's depth.

Docs

  • The guide describes void/og on its own, with no comparisons to or migration from other libraries.
  • New "Control font downloads" section: memory growth on long-running Node.js, Bun and Deno servers, subrequests and first-render latency on Workers, and fallbackFonts: false with the app's own fonts.
  • The Fonts section says your fonts come before Geist and names Noto as the fallback. The font example uses a Google Fonts URL.
  • The Worker size section states the renderer's cost (about 4.3 MB, 1.9 MB compressed).
  • Shorter void/og notes in packages/void/AGENTS.md.

Tests: 34 unit tests and 6 integration tests, covering the cases above.

Live demo with Latin, Japanese, Chinese, Korean, per-lang Han and weight cards: https://void-og-test.yangshun.workers.dev

Reviewer notes

  1. CPU time on Workers Free. A simple card takes ~10 ms of CPU, richer ones 30–80 ms, and the first render in a new isolate >100 ms, against Free's 10 ms per request. The guide tells Free users to cache image routes with routing.revalidate. These numbers are from Miniflare; CPU time on a deployed Worker hasn't been measured.
  2. Downloads while rendering. By default, text Geist can't draw fetches a font from Google Fonts, and emoji come from jsDelivr. Each download counts as a subrequest and slows the first render; a failed font draws boxes rather than failing the image. fallbackFonts: false opts out. Google's text= parameter has no documented length limit; Void falls back to the per-range files above 6,000 encoded characters, below where it was measured to stop working.
  3. Memory on Node.js, Bun and Deno. Each new title keeps ~37 KB of font data until restart, unbounded. Takumi's render() uses a default renderer without fontCacheMaxBytes. A follow-up could create Void's own renderer with a cap. Documented for now.
  4. takumi-js install on Node.js targets. Apps must list takumi-js in dependencies, because the native addon can't be bundled and the production install fetches the right binary for the server. Rendering with the Wasm build on Node.js instead was measured at 2.5–3× slower with ~70 MB more memory. Raising Void's ~2.20.0 range later will ask Node.js apps to update theirs (the build error names the command). I couldn't find a better way around this. I think this is fine for now and we can revisit this.
  5. Remote images. Markup can fetch remote images. Apps that put request values in image URLs should set images.allowUrl and maxBytes. Worth a security look.
  6. Known Takumi behaviors, documented or noted rather than worked around:
    • One Chinese style applies per image, chosen by lang.
    • Geist is built into Takumi and stays as the last fallback.
    • An element whose font-family names a font the image didn't pass can draw with it if an earlier image on the same server registered it. Plain text without font-family isn't affected.
  7. API narrowed from the original. The original passed Takumi's options through, including other output formats (JPEG, WebP, ICO). Those are gone. Happy to discuss if any were important.

@cpojer
cpojer requested a review from kossnocorp November 12, 2026 06:54
@cpojer

cpojer commented Nov 12, 2026

Copy link
Copy Markdown
Member

@kossnocorp could you review this PR and merge it when it's ready?

@kossnocorp

Copy link
Copy Markdown
Contributor

@cpojer on it

@kossnocorp

Copy link
Copy Markdown
Contributor

@yangshun @ogawa0071 heads up, I updated the branch via GitHub, and it force-pushed the branch 🫠 Forgot it does that. Be careful if want to pull.

@yangshun

Copy link
Copy Markdown
Collaborator

@kossnocorp No problem, I won't be pushing anything for now. You can make any changes you want.

@kossnocorp kossnocorp left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only critical issue is accepting HTML string.

I would still rename the module to void/image, but I'm not sure how to handle default image sizes. I would remove them in this PR and add OgImageResponse (imported from void/og) with presets like: "standard" | "x-large" | "x-small" | "linkedin".

Using xxHash would be a bit faster that SHA but I don't think it matters.

Comment thread docs/guide/og-images.md Resolved
Comment thread docs/guide/og-images.md Resolved
Comment thread docs/guide/og-images.md Resolved
Comment thread packages/image/src/generate/fonts.ts Resolved
Comment thread packages/void/src/runtime/og.ts Resolved
@kossnocorp

Copy link
Copy Markdown
Contributor

...and I would definitely use Inter instead of Geist.

@cpojer

cpojer commented Nov 12, 2026

Copy link
Copy Markdown
Member

I haven't spent time looking at the API yet, but I see two issues in the implementation:

  • It looks like Takumi's default font renderer retains fonts forever which leaks memory outside of workers. Can you bound fontCacheMaxBytes and make sure that font subsets are evicted in some form?
  • We should escape interpolated values by default to avoid accidentally injecting image tags or issuing requests. We should probably do something similar to Hono's html tag instead of accepting raw strings.

@kossnocorp

Copy link
Copy Markdown
Contributor

@cpojer you were right regarding Takumi munching memory:

image

One can load multiple fonts into single family and eat as much memory as they want. I had to implement custom cache 🫠

@ogawa0071

Copy link
Copy Markdown
Author

@kossnocorp

I would still rename the module to void/image, but I'm not sure how to handle default image sizes. I would remove them in this PR and add OgImageResponse (imported from void/og) with presets like: "standard" | "x-large" | "x-small" | "linkedin".

Thanks for the suggestion! I agree that generating images from JSX isn’t really specific to Open Graph, and I can see why grouping it under void/image is appealing.

Still, I’d prefer to keep void/og. The main goal of this module is to make moving from Next.js easy, and that works best when the differences are as small as possible. With the same module name and the same ImageResponse API, the JSX and options carry over unchanged, and only the import changes.

The next/image counterpart is already in a separate PR (#450), so keeping this one as void/og also keeps the two apart, as Next.js does with next/og and next/image.

For the default size, I’d suggest the same approach: keep only next/og’s 1200 × 630 default and let width and height cover everything else. One concern with presets named after networks like linkedin is that their recommended image sizes change often, so the presets would need updating to stay accurate, while width and height already handle any size. That said, I’m happy to go with whatever you think fits Void best.

@yangshun

Copy link
Copy Markdown
Collaborator

@kossnocorp Was fontCacheMaxBytes not working well? Why do we need a custom cache?

cc @kane50613 for input.

@kossnocorp

Copy link
Copy Markdown
Contributor

@yangshun the cache problem was in the eviction approach. It is family-based, but a family can contain any number of fonts. Here's the result after a fix:

image

@yangshun

Copy link
Copy Markdown
Collaborator

Thanks for the explanation. Maybe it's a feature request we can raise to Takumi

@kossnocorp

kossnocorp commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

@yangshun I understand the compatibility concern, but I think we have consensus with @cpojer here, void/image is much clearer API. I added OgImageResponse with a bunch of OG-specific niceties to void/og, see maybe you'll find the approach better.

Re PR to Takumi, that would probably be a nice thing to do, but I can't promise I'll get to it.


@ALL The PR is ready for a new round. I changed a lot of stuff:

  • Moved ImageResponse to void/image. I removed predefined size and set cache headers making it a generic JSX/HTML -> image renderer.

  • Added void/og with OgImageResponse:

    import { html } from 'void/html';
    import { OgImageResponse } from 'void/og';
    
    export const GET = () =>
      new OgImageResponse(<div style="display: flex; font-size: 72px">Hello, world!</div>, {
        // X has 1200 × 600. If omitted defaults to standard 1200 × 630.
        // It includes platform-specific presets for Discord, Pinterest, etc.
        // Can be used with width and height too.
        preset: 'x', 
      });
  • Removed default cache header from ImageResponse and set 24 hrs max age in production for OgImageResponse unless overriden. There are mixed reports about platform's caching but the number I found were pretty conservative, i.e., 7 days. So I used the chance to apply sensible defaults to this OG-specific class.

  • ImageResponse now reject strings and expects sanitized HTML via html literal template that users can import from void/html. It reexports hono/html. There's also raw helper that can be interpolated into html to use when it makes sense.

  • Removed the need to add takumi-js to dependencies. To do that I had to switch to using Wasm instead of native modules for Bun and Node.js

  • Bundled and set Inter as the default font.

  • Fixed the fonts cache memory leak. The cache system also checks for pending renders to stop breaking concurrent image requests.

  • Also added a dev playground to experiment with different styles, options and variations.

@void/image vs void/image

I don't think we really have to publish it as @void/image (with @void/image/og) as I managed to remove the need for manually managingtakumi-js. I think it is fine now.

I also tested Cloudflare's Kitesurf browser and Cloudflare Browser Run as additional renderers. We might consider adding them in the future and making the worker builds lighter, but it turned out Takumi is much faster ~50ms vs Browser Run ~500ms and Kitesurf 1000+ms. So they don't solve the immediate problem and add another.

I would consider having Browser Run as the default renderer for OgImageResponse for Cloudflare/Void Platform deployments as latency is not essential there. We can do it dynamically.

Similarly for Cloudflare-based deployments we can replace ImageResponse renderer with calls to service wrapping Takumi and solve the deployment size problem without changing API.

@yangshun

yangshun commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

void/image is much clearer API.

Sounds good!

I would consider having Browser Run as the default renderer for OgImageResponse for Cloudflare/Void Platform deployments as latency is not essential there. We can do it dynamically. Similarly for Cloudflare-based deployments we can replace ImageResponse renderer with calls to service wrapping Takumi and solve the deployment size problem without changing API.

In my updates I constrained the API to be the minimum we need (aligning with next/og's) and there aren't Takumi-specific props. That should help with switching renderers in future if there's ever a need.

@kossnocorp Thanks for the good work!

@kane50613

Copy link
Copy Markdown

@kossnocorp Was fontCacheMaxBytes not working well? Why do we need a custom cache?

cc @kane50613 for input.

Thanks for taking effort to bring Takumi into Void and reporting, I'm traveling right now will check on that ASAP

@ogawa0071

Copy link
Copy Markdown
Author

@kossnocorp Thanks for the good work!
My only question is about the Image component in #450: would it also be imported from this module, as import { Image } from "void/image"?
I think we still need a component that replaces the <img> tag and handles image transformation, separately from ImageResponse, so I’d like to check that both are meant to live in void/image.

yangshun and others added 24 commits November 18, 2026 07:59
Keep what maintainers act on: the declared options, the Node.js, Bun and
Deno install check, and the Takumi upgrade steps. The font and Wasm
details already live in the source comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cloudflare now limits a Worker to 64 MiB uncompressed on every plan and
has no compressed limit, so the guide no longer counts down from 3 MB.
It keeps what the renderer costs: 4.3 MB more to upload and to start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Text with Hangul draws Han characters with Noto Sans KR, so both scripts
asked for the same family, and the Hangul request replaced the Han one.
"日本語・中文・한국어" drew its Han characters, and the numbers beside them,
as boxes. Ask the family for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cpojer cpojer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is awesome, I'm excited about shipping this!

There are a few more issues:

  • Node crash: When you have an unread image response, it can crash Node.js with an unhandled rejection. Try by constructing an ImageResponse from an async html template, cancel its body and let the template reject.
  • Module loading: This PR overwrites how @void/image is loaded, so if in the future there is a dependency that uses @void/image that's different from the one in the app, you might get the wrong one. We should probably not mess with that.
  • React components: renderImage(<Card />) works when Card is written as a function, but breaks with React class components. We should make class components work since the types say they are working.
  • Fonts: .woff appears to work in Takumi (and is listed in the docs), but the renderer in Void does not support it. .woff2 appears to work.
  • Caching: It seems that this PR sets a one-minute caching header in development for SVG's even if @void/image is not used. We should only do this for generated images.

Please also update the package.json version to 1.10.0 (current released Void version).

@kane50613

Copy link
Copy Markdown

woff appears to work in Takumi (and is listed in the docs), but the renderer in Void does not support it. .woff2 appears to work

In order to minimize WASM size woff is turned off on wasm builds and only enabled for node (napi) builds

FYI I'm work on new unified caching module to allow more flexibility and address questions in this discussion thread

I'd love to answer more questions if needed

@cpojer

cpojer commented Nov 18, 2026

Copy link
Copy Markdown
Member

Yup that's fine, but then we should throw and not say in the docs that we support it.

@kane50613

Copy link
Copy Markdown

works when Card is written as a function, but breaks with React class components.

I guess this is a bug in upstream Takumi, will take a look and fix in next release if needed

@kane50613

Copy link
Copy Markdown

works when Card is written as a function, but breaks with React class components.

I guess this is a bug in upstream Takumi, will take a look and fix in next release if needed

Update: kane50613/takumi#2596 fixed it

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

next/og compatible function built on Satori

5 participants