Skip to content
Tinbox

tutorials

How to send email from a Next.js app on Cloudflare

November 9, 2026

#nextjs#cloudflare#email#transactional-email#tutorial
Interlocking email tool modules illustrate a composable developer interface.

You moved your Next.js app to Cloudflare for the cold starts and the price, added nodemailer to a route handler, and the build broke with No such module "net". Here is why, and what to send mail with instead.

To send transactional email from a Next.js app deployed on Cloudflare, the most portable path is a Worker-native binding or HTTPS API from a route handler or Server Action. Workerd exposes outbound TCP, but not Node's full socket runtime; Node-oriented SMTP packages such as Nodemailer are therefore not automatically compatible, outbound port 25 is blocked, and Cloudflare-owned SMTP endpoints are unreachable over Worker TCP. Use a Worker-native helper or fetch() unless you have deliberately chosen and tested a runtime-compatible third-party submission client.

This is one of those problems where the error message doesn't tell you the real story, so let's walk the whole thing: what breaks, why it breaks, the manual fix with a hosted API, and the edge-native version.

Why doesn't nodemailer work in Next.js on Cloudflare?

nodemailer doesn't work because Cloudflare runs your Next.js app on workerd, a V8-based runtime that is not Node.js. nodemailer opens a raw TCP socket to an SMTP server using Node's net and tls modules, and those modules aren't available on workerd in the way the library needs. On top of that, outbound port 25 is blocked across Cloudflare's network.

When you deploy a Next.js app to Cloudflare you're using one of two adapters:

  • @cloudflare/next-on-pages (Pages-based), or
  • @opennextjs/cloudflare (OpenNext, Workers-based, now the recommended path).

Both compile your route handlers, Server Actions, and middleware to run on workerd. Your app/api/*/route.ts files do not run on a Node server. That single fact is what breaks SMTP.

Here's the code that looks fine and isn't. A route handler that sends a welcome email:

// app/api/welcome/route.ts
import nodemailer from "nodemailer";

export async function POST(req: Request) {
  const { email } = await req.json();

  const transport = nodemailer.createTransport({
    host: "smtp.example.com",
    port: 587,
    auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
  });

  await transport.sendMail({
    to: email,
    from: "hello@yourdomain.com",
    subject: "Welcome",
    text: "Thanks for signing up.",
  });

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

Depending on your adapter and bundler, this fails in one of a few ways. At build/bundle time:

✘ [ERROR] Could not resolve "net"
    node_modules/nodemailer/lib/smtp-connection/index.js
  The package "net" wasn't found on the file system but is built into node.

If you add nodejs_compat and it bundles, you push the failure to runtime instead:

Error: Connection timed out
  at TCPSocket.connect (smtp.example.com:587)
TypeError: Cannot read properties of undefined (reading 'createConnection')

People hit this and reach for nodejs_compat in Wrangler config, hoping the compatibility flag makes a Node SMTP package drop in unchanged. It does not. Workers expose their own connect() socket API, while Node mailers expect Node's socket behavior; library compatibility is separate from whether a destination port is allowed. Direct-to-MX port 25 remains a hard network boundary.

What about Cloudflare's connect() TCP socket API?

Cloudflare ships a connect() TCP socket API. It cannot connect to port 25, so it cannot deliver directly to recipient MX servers. It also cannot connect to Cloudflare-owned IP ranges, which rules out Cloudflare's own authenticated SMTP host. A deliberately Worker-native client can connect to an allowed third-party submission service on ports such as 465 or 587, but Node mailers are not automatically compatible and the request path still needs timeout, retry, and idempotency design. For this guide, the portable path is Cloudflare's native binding or an HTTPS API.

How do I actually send email from a Next.js route on Cloudflare?

Send over HTTPS from server-side code: call an email provider's REST API with fetch(), or use a Worker-native send helper. Your route handler stays an HTTPS request and never opens a socket. Here is the manual, provider-API version first, done completely, then the edge-native shortcut.

Step 1: Keep the send on the server

Email sends must be server-side so your API key never reaches the browser. In Next.js that means a route handler (app/api/*/route.ts) or a Server Action. Both run on workerd server-side. Never put a send in a client component or behind a NEXT_PUBLIC_ variable.

Step 2: Read secrets from the Cloudflare env, not process.env

This is the gotcha that costs people an afternoon. On Cloudflare, your secrets live in the Worker environment, not in Node's process.env. With OpenNext you read them through getCloudflareContext():

// app/api/welcome/route.ts
import { getCloudflareContext } from "@opennextjs/cloudflare";

export async function POST(req: Request) {
  const { email } = await req.json();
  const { env } = getCloudflareContext();
  const apiKey = env.EMAIL_API_KEY; // a Worker secret, not process.env

  if (!apiKey) {
    return Response.json({ error: "EMAIL_API_KEY not bound" }, { status: 500 });
  }
  // ...send below
}

Set that secret with Wrangler so it never lands in your repo:

npx wrangler secret put EMAIL_API_KEY
✔ Enter a secret value: ********
✨ Success! Uploaded secret EMAIL_API_KEY

Step 3: Send with fetch()

Now do the actual send over HTTPS. Every reputable provider exposes a JSON API; the shape is roughly the same across them. A complete handler:

// app/api/welcome/route.ts
import { getCloudflareContext } from "@opennextjs/cloudflare";

export async function POST(req: Request) {
  const { email } = await req.json();
  const { env } = getCloudflareContext();

  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: email,
      subject: "Welcome",
      html: "<p>Thanks for signing up.</p>",
    }),
  });

  if (!res.ok) {
    const detail = await res.text();
    return Response.json({ error: "send failed", detail }, { status: 502 });
  }

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

That works. It's the honest baseline: a server-side route, a secret read from the Cloudflare env, and an HTTPS call. No SMTP, no socket, nothing that trips workerd.

Step 4: Don't block the response on the send (optional but worth it)

A subtle issue with the above: if the provider is slow, your user waits. Workers give you waitUntil() so you can return immediately and let the send finish in the background:

import { getCloudflareContext } from "@opennextjs/cloudflare";

export async function POST(req: Request) {
  const { email } = await req.json();
  const { env, ctx } = getCloudflareContext();

  const send = 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: email,
      subject: "Welcome",
      html: "<p>Thanks for signing up.</p>",
    }),
  });

  ctx.waitUntil(send); // finishes after the response returns
  return Response.json({ ok: true });
}

The cost: you've now decoupled the response from the result, so a failed send is invisible to the caller unless you log it or push it onto a queue for retries. For receipts and password resets, where the user is waiting on the email, you usually want to know it sent. For best-effort notifications, fire-and-forget is fine. This tension (fast response vs. knowing the send succeeded) is exactly what a queue solves, which is where the edge-native option earns its keep. The reliability patterns a queue brings (automatic retries, a dead-letter path, idempotent consumers) are laid out in the Cloudflare Queues patterns for reliable email sending.

What's the edge-native way to send from Next.js on Cloudflare?

The edge-native way is to enqueue the message on your own Cloudflare account and let a consumer Worker do delivery, so your route returns instantly and retries happen off the request path. You get the waitUntil() speed and delivery guarantees, without standing up a queue and a consumer yourself. tinbox/cf is a library that does this, running entirely on your Cloudflare account (D1, R2, Queues) rather than a third-party SaaS.

This is the "or skip all of the above" shortcut. The provider-API path is perfectly good; this one trades the external account for resources you already own.

Step 1: Initialize Tinbox on your domain

npx tinbox init yourdomain.com

This scaffolds the email Worker, provisions D1/R2/Queues on your Cloudflare account, and prints the DNS records that make outbound mail deliverable (SPF, DKIM, DMARC). Without those three records your mail lands in spam no matter how you send it:

✔ 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: Bind the resources to your Next.js Worker

Add the bindings to your Wrangler config (with OpenNext this is the config the adapter deploys):

// wrangler.jsonc
{
  "name": "my-next-app",
  "main": ".open-next/worker.js",
  "compatibility_date": "2026-06-01",
  "compatibility_flags": ["nodejs_compat"],
  "d1_databases": [
    { "binding": "TINBOX_DB", "database_name": "tinbox-yourdomain-db" }
  ],
  "r2_buckets": [
    { "binding": "TINBOX_MAIL", "bucket_name": "tinbox-yourdomain-mail" }
  ],
  "queues": {
    "producers": [
      { "binding": "TINBOX_SEND", "queue": "tinbox-yourdomain-send" }
    ]
  }
}

Step 3: Send from the route handler

The handler that broke at the top of this article now works, because under the hood it's an HTTPS-shaped enqueue, not a socket:

// app/api/welcome/route.ts
import { getCloudflareContext } from "@opennextjs/cloudflare";
import { tinbox } from "tinbox/cf";

export async function POST(req: Request) {
  const { email } = await req.json();
  const { env } = getCloudflareContext();

  await tinbox(env).send({
    to: email,
    from: "hello@yourdomain.com",
    subject: "Welcome",
    html: "<p>Thanks for signing up.</p>",
  });

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

tinbox(env).send(...) writes the message onto your Cloudflare Queue and returns immediately, so the route is fast. A consumer Worker picks it up, signs it with DKIM, delivers it over a path that's allowed to talk to the world, and records bounces and complaints back into your D1 database. Your Next.js route never opens a socket and never blocks on remote delivery.

Step 4: Deploy

npx opennextjs-cloudflare build && npx wrangler deploy
Total Upload: 2.41 MiB / gzip: 0.52 MiB
Uploaded my-next-app (4.18 sec)
Deployed my-next-app
  https://my-next-app.yourdomain.workers.dev
Current Version ID: 7c2a...

Hit the route, and the mail goes out DKIM-signed and SPF-aligned, with bounce tracking, no nodemailer, no net module, no port 25.

Common failure modes and what they mean

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

Could not resolve "net" / "tls" / "dns"

You still have an SMTP library (nodemailer, smtp-client, etc.) in the import graph. Remove it; nothing in the SMTP family bundles cleanly for workerd. Switch to an HTTPS send.

env.EMAIL_API_KEY is undefined

You read process.env instead of the Cloudflare env, or you never set the secret. Read via getCloudflareContext().env and run npx wrangler secret put EMAIL_API_KEY.

TINBOX_SEND is not defined

You called tinbox(env).send() before binding the queue. Add the queues.producers block to your Wrangler config and redeploy.

Mail accepted but landing in spam

DNS isn't fully there yet. Run npx tinbox doctor to confirm SPF, DKIM, and DMARC resolve and that your DKIM selector matches the signing key. New domains also need warmup; reputation isn't instant.

Where to go from here

The send is one piece. The deeper questions are why the edge forces HTTPS at all, and what owning the sender buys you:

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 API.

Frequently asked questions

Why does nodemailer fail in a Next.js app on Cloudflare?

Nodemailer assumes Node's net/tls socket and connection lifecycle, while Workers expose a different connect() API; compatibility depends on the adapter/runtime rather than SMTP being categorically absent. Direct-to-MX port 25 is blocked, and Cloudflare-owned SMTP endpoints are unreachable from Worker TCP.

How do I send transactional email from a Next.js route on Cloudflare?

Use a native Email Service binding or HTTPS API from a server-side route handler or server action. Workers expose outbound connect(), but direct-to-MX port 25 and Cloudflare-owned SMTP endpoints are blocked, and Node SMTP libraries are not drop-in compatible. A tested Worker-native client to an allowed third-party submission service is possible, but it should not sit inline in a latency-sensitive request without queueing and idempotency.

Can I send email from a Next.js Server Action on Cloudflare?

Yes. Server Actions run server-side on the same workerd runtime as route handlers, so a Worker-native binding or HTTPS send works inside them. Outbound connect() exists, but Node SMTP libraries are not drop-in compatible and port 25 remains blocked.

Does this apply to next-on-pages and OpenNext both?

Yes. Both adapters compile the application for workerd. Neither removes the port-25 block or guarantees that a Node SMTP package maps to Workers connect(). A native binding or HTTPS API works under both; a Worker-native third-party SMTP client needs its own compatibility tests.

Where do I keep the email API key in a Next.js Cloudflare deployment?

As a Worker secret or an environment binding, read on the server only. With OpenNext you read it from the Cloudflare env via getCloudflareContext(); never expose it to a client component or a NEXT_PUBLIC_ variable.