Send email from Node.js and Next.js with an email API, without duplicates or lost mail

· 2 min read

Code to send email from Node.js and Next.js with plain fetch and no library, plus safe retries with an Idempotency-Key and handling the errors you'll actually see.

Send email from Node.js and Next.js

Node.js can send email with its built-in fetch, no library needed. Most of the trouble comes later: a network hiccup makes you retry and the customer gets two emails, or an error fails silently and the email is lost.

Before you start

  1. Verify the domain you'll send from in the Dashboard
  2. Create an API key and store it in an environment variable named BYTESMS_API_KEY
  3. Never put the API key in browser code; call the API from the server only

Your first email

const res = await fetch("https://api.bytesms.com/api/v1/emails", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    from: "Your Shop <[email protected]>",
    to: ["[email protected]"],
    subject: "Order #1024 confirmed",
    html: "<p>Thanks for your order</p>",
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.name}: ${data.message}`);
console.log(data.id); // store the id with the order

If you only pass html, a text/plain part is generated for you, which helps inbox placement.

Retry safely with an Idempotency-Key

If the connection drops after you send the request, you can't tell whether the email was accepted. Send an Idempotency-Key header tied to the event, such as order-1024-confirmation, and retry with the same key: the email is accepted once and every retry gets the original id back. Keys are remembered for 24 hours.

async function sendOnce(payload, key, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    try {
      const res = await fetch("https://api.bytesms.com/api/v1/emails", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": key,
        },
        body: JSON.stringify(payload),
      });
      if (res.status === 429 || res.status >= 500) {
        const wait = Number(res.headers.get("retry-after") ?? 2 ** i);
        await new Promise((r) => setTimeout(r, wait * 1000));
        continue;
      }
      return await res.json();
    } catch {
      await new Promise((r) => setTimeout(r, 2 ** i * 1000));
    }
  }
  throw new Error("send failed after retries");
}

Next.js: send from a Route Handler

// app/api/contact/route.ts
export async function POST(req: Request) {
  const { email, message } = await req.json();
  const res = await fetch("https://api.bytesms.com/api/v1/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: "Website <[email protected]>",
      to: ["[email protected]"],
      reply_to: email,
      subject: "New message from the website",
      text: message,
    }),
  });
  return Response.json(await res.json(), { status: res.status });
}

Errors to handle

Status name Meaning
401 unauthorized Wrong or expired API key
403 invalid_from_address From isn't on a verified domain
409 idempotency_key_conflict Same key reused with a different body; use a new key
422 validation_error Missing or malformed fields; details in message
429 rate_limit_exceeded Too fast; wait for retry-after
429 daily_quota_exceeded The plan's daily quota is used up

Branch on name and status, never on the message text, which can change. To send many emails at once, POST /api/v1/emails/batch takes up to 100 per request.

More articles