Skip to content
Tinbox

tutorials

Render React Email templates on Cloudflare Workers

October 23, 2026

#react-email#cloudflare-workers#email-templates#edge#tutorial
A code module connects to a press producing product emails.

You write your transactional emails as React components, moved your sender to a Worker, dropped in @react-email/render, and the build died on Could not resolve "stream". React Email was built for Node. Here is how to get it rendering on the edge, and when not to render at all.

To render React Email templates inside a Cloudflare Worker, call the async render() from @react-email/render, fix the bundler by adding nodejs_compat (or marking react-dom external), and keep heavy rendering off the request path by precompiling static templates to HTML at build time. React Email is built on react-dom/server, which can run on workerd, but the library and its transitive dependencies assume Node in a few places that you have to work around.

This is a "it almost works, then doesn't" problem, so let's go through it completely: what breaks, why, the manual fix done properly, the build-time approach that's actually the right call at volume, and the shortcut.

Does React Email work on Cloudflare Workers?

React Email works on Cloudflare Workers with two fixes: a bundler fix so it compiles, and a runtime fix so the render doesn't throw. The core renderer is react-dom/server, which is portable, but @react-email/render historically pulled in Node-only paths and some components reach for built-ins like stream and util. The workerd runtime is V8-based, not Node, so those resolve to nothing unless you tell the bundler what to do.

Here is the code that looks fine. A Worker that renders a welcome email:

// src/index.tsx
import { render } from "@react-email/render";
import { Html, Head, Body, Container, Text } from "@react-email/components";

function WelcomeEmail({ name }: { name: string }) {
  return (
    <Html>
      <Head />
      <Body>
        <Container>
          <Text>Welcome, {name}. Thanks for signing up.</Text>
        </Container>
      </Body>
    </Html>
  );
}

export default {
  async fetch(req: Request): Promise<Response> {
    const html = await render(<WelcomeEmail name="Ada" />);
    return new Response(html, { headers: { "content-type": "text/html" } });
  },
};

Run wrangler deploy against that and, depending on your version of the library and your bundler config, you get one of these. At bundle time:

✘ [ERROR] Could not resolve "stream"

    node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:11:25:
      11 │ var stream = require('stream');
✘ [ERROR] Could not resolve "util"

    node_modules/@react-email/render/dist/node/index.js
  The package "util" wasn't found on the file system but is built into node.

Or it bundles and then throws at runtime when the renderer hits a Node-only Promise path:

TypeError: Cannot read properties of undefined (reading 'renderToReadableStream')

The root cause is that react-dom/server ships several entry points: a Node one (react-dom/server.node) that uses stream, an edge one (react-dom/server.edge) that uses Web Streams, and a browser one. @react-email/render doesn't always pick the edge entry for you, and bundlers targeting workerd don't know to substitute it. So you either point the bundler at the right thing or give it the Node compatibility shims.

How do I fix the React Email bundling error on Workers?

Fix the bundling error by adding the nodejs_compat flag to your Wrangler config, which provides workerd's polyfills for stream, util, and friends. This is the lowest-friction fix and it's the one to reach for first.

// wrangler.jsonc
{
  "name": "email-renderer",
  "main": "src/index.tsx",
  "compatibility_date": "2026-06-01",
  "compatibility_flags": ["nodejs_compat"]
}

With nodejs_compat on, the stream/util imports resolve to workerd's implementations and the bundle succeeds. Unlike SMTP (where the compat flag is a dead end because the underlying capability is missing), here the missing thing is genuinely just a handful of Node module shims, and workerd has them.

If you'd rather not pull in the Node compat surface, the alternative is to point the renderer at the edge build of react-dom/server and externalize the Node entry. With esbuild-style config:

// wrangler.jsonc
{
  "name": "email-renderer",
  "main": "src/index.tsx",
  "compatibility_date": "2026-06-01",
  "alias": {
    "react-dom/server": "react-dom/server.edge"
  }
}

The alias maps any import of react-dom/server to the Web Streams edge build, which needs no Node modules. Use whichever you prefer; nodejs_compat is simpler, the alias is leaner. Both get you a clean bundle.

That handles compilation. The runtime fix is to make sure you're calling the async render():

// Correct: the async render() resolves to a string on workerd
const html = await render(<WelcomeEmail name="Ada" />);

// Wrong on the edge: the sync helper can hit the Node stream path
import { renderToStaticMarkup } from "react-dom/server";
const html = renderToStaticMarkup(<WelcomeEmail name="Ada" />); // may throw

@react-email/render's top-level render() returns a Promise and, on the edge build, uses renderToReadableStream under the hood, which is the path that behaves. Always await it.

Should I render React Email at request time or build time?

Render static templates at build time and only do string interpolation per request. Rendering full JSX to HTML on every send burns Worker CPU and, at campaign volume, will push you against CPU-time limits for no benefit, because the markup is identical except for a few variables.

This is the part most tutorials skip, and it's the part that matters in production. A transactional template is 99% static. The right shape is: render the React component to an HTML string once, at build time, with placeholder tokens where the dynamic data goes; ship that string; and at send time do a cheap replace.

Step 1: Author the template with tokens

// emails/welcome.tsx
import { Html, Head, Body, Container, Text, Button } from "@react-email/components";

export default function WelcomeEmail() {
  return (
    <Html>
      <Head />
      <Body style={{ fontFamily: "sans-serif" }}>
        <Container>
          <Text>Welcome, {"{{name}}"}. Your account is ready.</Text>
          <Button href={"{{confirmUrl}}"}>Confirm your email</Button>
        </Container>
      </Body>
    </Html>
  );
}

The {{name}} and {{confirmUrl}} are literal strings in the JSX, so they survive rendering as plain tokens in the output HTML.

Step 2: Compile to HTML at build time

A small Node build script (this runs in your CI/build, not in the Worker, so Node is fine here):

// scripts/build-templates.ts
import { render } from "@react-email/render";
import { writeFile } from "node:fs/promises";
import WelcomeEmail from "../emails/welcome";

const html = await render(WelcomeEmail(), { pretty: false });
await writeFile("src/templates/welcome.html", html);
console.log("compiled welcome.html");
$ npx tsx scripts/build-templates.ts
compiled welcome.html

You now have a flat HTML file with {{name}} and {{confirmUrl}} still in it. Import it as a string asset (or store it in D1) and ship it with the Worker.

Step 3: Interpolate at send time, cheaply

In the Worker, do string substitution with proper escaping. No JSX, no react-dom, no per-request render cost:

// src/render.ts
function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

export function fill(template: string, vars: Record<string, string>): string {
  return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
    const v = vars[key];
    return v === undefined ? "" : escapeHtml(v);
  });
}
// src/index.ts
import welcomeHtml from "./templates/welcome.html";
import { fill } from "./render";

export default {
  async fetch(req: Request): Promise<Response> {
    const { name, confirmUrl } = await req.json();
    const html = fill(welcomeHtml, { name, confirmUrl });
    // hand html to your sender (see below)
    return Response.json({ ok: true, bytes: html.length });
  },
};

The Worker now does a regex replace instead of a React render. That's the difference between a few microseconds and a few milliseconds of CPU per email, which compounds hard when you're sending a campaign to fifty thousand people. Reserve request-time rendering for genuinely one-off, deeply dynamic mail.

A note on the Tailwind component

React Email's <Tailwind> component is convenient but it runs the Tailwind compiler during render. That's tolerable once at build time and painful on every request. If you use Tailwind in your templates, compile at build time without exception, then ship the inlined-CSS HTML. Don't put the Tailwind compiler on the edge hot path.

How do I send the rendered email from a Worker?

Send the rendered HTML over HTTPS, not SMTP, because Cloudflare Workers cannot open outbound port 25 for direct-to-MX SMTP. Rendering and sending are two separate problems; the renderer above produces an HTML string, and the string still has to leave the edge over a path workerd allows.

// pass the rendered HTML to an HTTPS email API
const res = await fetch("https://api.your-email-provider.com/v1/send", {
  method: "POST",
  headers: {
    authorization: `Bearer ${env.EMAIL_API_KEY}`,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    from: "hello@yourdomain.com",
    to: recipient,
    subject: "Welcome",
    html, // the filled template from above
  }),
});

If you try to wire SMTP instead, you'll hit the same wall every edge email project hits. The full explanation lives in why you cannot send email from a Worker, but the short version: render at the edge, deliver over HTTPS. The HTTPS-versus-SMTP confusion is one of several recurring misreads in the myths about sending email from Cloudflare Workers, and the ways to send email from Cloudflare Workers compares the transports that actually work.

The edge-native shortcut: precompiled templates done for you

The "or skip all of this" version is to let Tinbox own the template pipeline, so the Worker never renders JSX on the request path and you never hand-roll the build script, the token escaping, or the bundler workaround. Tinbox runs entirely on your Cloudflare account (D1, R2, Queues, Workers), so the templates and the rendered HTML stay in resources you own.

The manual path above is genuinely fine, and if you only have two or three templates, do it by hand: it's not much code. Tinbox is the shortcut when you want the build-time compilation, the variable store, and the queue-backed sender wired together already.

Step 1: Initialize on your domain

npx tinbox init yourdomain.com
✔ Provisioned D1 database (tinbox-yourdomain-db)
✔ Provisioned R2 bucket (tinbox-yourdomain-mail)
✔ Provisioned Queue (tinbox-yourdomain-send)

Add these DNS records to yourdomain.com:

  TXT  @                  v=spf1 include:_spf.yourdomain.com ~all
  TXT  tinbox._domainkey  v=DKIM1; k=rsa; p=MIIBIjANBg...
  TXT  _dmarc             v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com

Once DNS propagates, run: npx tinbox doctor

Step 2: Store a template with variables

Templates compile once and live in your D1, with {{tokens}} for the dynamic fields. At send time Tinbox interpolates and escapes, then enqueues for delivery:

import { tinbox } from "tinbox/cf";

export default {
  async fetch(req: Request, env: Env) {
    const { email, name, confirmUrl } = await req.json();

    await tinbox(env).send({
      to: email,
      from: "hello@yourdomain.com",
      subject: "Welcome",
      template: "welcome",        // the precompiled template id
      vars: { name, confirmUrl }, // interpolated + escaped, then queued
    });

    return Response.json({ ok: true });
  },
};

tinbox(env).send(...) resolves the template, fills the variables, writes the message onto your Cloudflare Queue, and returns immediately. A consumer Worker DKIM-signs and delivers it over an HTTPS path that's allowed to talk to the world, and records bounces back into your D1. No per-request JSX render, no stream module error, no SMTP socket.

Step 3: Deploy

npx wrangler deploy
Total Upload: 1.93 MiB / gzip: 0.41 MiB
Uploaded email-renderer (3.62 sec)
Deployed email-renderer
Current Version ID: a91f...

Common failure modes and what they mean

A few errors you'll hit, so you don't debug them blind:

Could not resolve "stream" / "util"

The bundler is pulling the Node build of react-dom/server. Add nodejs_compat, or alias react-dom/server to react-dom/server.edge. One of those, not both.

TypeError: Cannot read properties of undefined (reading 'renderToReadableStream')

You called a sync render helper, or an old @react-email/render. Use await render(...) from a current version, which routes through the edge stream API.

Worker exceeded CPU time limit

You're rendering JSX per request at volume. Move to build-time compilation with token interpolation; the per-send work should be a string replace, not a React render.

Rendered email shows raw {{name}} in the inbox

Your interpolation step didn't run, or the token names don't match. Confirm the build-time HTML still contains the tokens and that your vars keys match them exactly.

Where to go from here

Rendering is one slice of an edge email stack. The adjacent problems are templating reuse, the send transport, and the deliverability records that decide whether any of it reaches the inbox:

One honest caveat: Tinbox deploys one brand and domain per instance today. You run many tenants by deploying multiple times on the same Cloudflare account; multi-domain-per-instance is designed but not yet built.

Deploy this yourself: npx tinbox init yourdomain.com, then read the docs for the full tinbox/cf template and send API.

Frequently asked questions

Does React Email work on Cloudflare Workers?

Partially. @react-email/render builds on react-dom/server, which runs on workerd, but you must call the async render() (not renderToStaticMarkup directly), keep heavy rendering off the hot path, and either add the nodejs_compat flag or mark react-dom as external so the bundler does not try to polyfill Node internals. Precompiling templates to HTML at build time avoids the runtime cost entirely.

Why does @react-email/render fail to bundle for a Worker?

Older versions and some transitive deps reach for Node built-ins (stream, util) and a synchronous render path that assumes Node. The bundler either errors with 'Could not resolve "stream"' or the render throws at runtime. Adding nodejs_compat or externalizing react-dom resolves the bundling; using the async render() resolves the runtime path.

Should I render React Email at request time or build time on Cloudflare?

Build time when the template is static, request time only for the dynamic parts. Rendering full JSX to HTML per request burns Worker CPU and risks hitting limits under load. Precompile each template to an HTML string with placeholder tokens, ship that as an asset or D1 row, and do cheap string interpolation per send.

Can I use React Email's Tailwind component on Workers?

Yes, but it runs the Tailwind compiler at render time, which is expensive on the edge. Prefer compiling Tailwind-based templates at build time and shipping the inlined-CSS HTML, then interpolate variables at send time. Reserve runtime rendering for low-volume, highly dynamic emails.

How do I pass dynamic data into a precompiled email template on a Worker?

Render the React Email template once at build time with placeholder tokens (for example {{name}}), store the resulting HTML, and at send time replace tokens with escaped values. This keeps the Worker doing string work instead of JSX rendering, which is both faster and cheaper per email.