Sending OTP emails from Node.js: a checklist

18 November 2026 · 7 min read

One-time passcodes by email look simple: generate six digits, send them, check them. Most of the problems show up later: codes that arrive after a minute, users who get two codes, codes guessed by a script, emails in spam. This checklist covers both the security side and the delivery side, with Node.js examples.

1. Generate codes securely

Use a cryptographically secure generator, not Math.random():

js
import { randomInt } from "node:crypto";
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");

2. Store a hash, not the code

Treat the code like a short-lived password. Store a hash with an expiry, and compare in constant time:

js
import { createHash, timingSafeEqual } from "node:crypto";
const hash = (c) => createHash("sha256").update(`${userId}:${c}`).digest();
// save { userId, hash: hash(code), expiresAt: Date.now() + 10 * 60_000, attempts: 0 }
const ok = timingSafeEqual(saved.hash, hash(input)) && Date.now() < saved.expiresAt;

3. Limit attempts and expiry

4. Send it with priority, and only once

The user is staring at the screen, so the email has to leave immediately and never twice. With TrivSend's Node.js SDK:

js
import { TrivSend } from "trivsend";
const trivsend = new TrivSend(process.env.TRIVSEND_API_KEY);

await trivsend.emails.send(
  {
    from: "Acme <noreply@notify.acme.com>",
    to: user.email,
    subject: `Your Acme code: ${code}`,
    text: `Your sign-in code is ${code}. It expires in 10 minutes. If you didn't ask for it, ignore this email.`,
    priority: "high",
  },
  { idempotencyKey: `otp-${requestId}` },
);

5. Write it for the inbox

6. Send from an authenticated domain

Use a subdomain such as notify.yoursite.com with SPF, DKIM and DMARC set up (how they work). Without them, Gmail and Outlook are much more likely to filter your codes.

7. Know when it didn't arrive

When a user says "I never got the code", you need to know whether the email was delivered, bounced or is still being retried. TrivSend shows this for every email, and a webhook can tell your app about bounces so you can suggest checking the address.

8. Test without sending

In CI, use test API keys and simulator addresses, so sign-up tests don't send real mail or count against your limits (testing).

Checklist

Send OTP emails with TrivSend, free for 3,000 emails a month.