OTP verification in Node.js: the full verify flow, sessions, rate limits and tests
Written and reviewed by the DiOTP team Published 30 November 2026Last updated 3 December 2026
10 min read
OTP verification in Node.js has two halves: sending a code is one API call, but verifying it safely is where the real work is. This guide builds the verify side properly in Express: the full flow from send to sign-in, the session that holds each pending request, per-IP rate limits in front of DiOTP's own limits, signed webhooks and a test suite you can run on every commit. It uses the official Node.js SDK, installed with npm install @diorbit/diotp.
How does OTP verification in Node.js work?
DiOTP generates the code, sends it, stores it and checks it. Your server never sees the digits. Your job is to ask for a code, keep the request_id that comes back somewhere the user cannot tamper with, and later ask DiOTP whether the code the user typed matches. The flow has four steps:
- The browser or app posts a phone number to POST /api/otp/send on your server.
- Your server checks the number and its own rate limit, asks DiOTP for a code and saves the request_id in the user's session.
- The user types the code. The client posts only the code to POST /api/otp/verify.
- Your server sends the saved request_id and the code to DiOTP. A successful reply means the number is proven, so you regenerate the session and sign the user in.
The API key must stay on your server. A key shipped in a web page or mobile app can be read by anyone, and they could send codes on your account until you revoke it.
Set up the project
You need Node 18 or newer. Create a project, set "type": "module" in package.json so the import syntax works, and install Express, its session and rate-limit middleware, and the official DiOTP SDK. For the tests at the end, add supertest as a development dependency.
Terminal
mkdir otp-backend && cd otp-backend
npm init -y
npm pkg set type=module
npm install express express-session express-rate-limit diotp
npm install --save-dev supertestCreate a key under API keys in the DiOTP dashboard and put it in an environment variable called DIOTP_API_KEY; the SDK reads it from there. Add a long random SESSION_SECRET for the session cookie. Never commit either value to Git.
If you only want the quickest possible setup, with a plain fetch client and no SDK, follow send OTP without DLT in Node.js instead. It also shows the exact SMS your users receive and how to read every error code. This guide goes deeper on the verify side.
The send route: start a verification
The app is built by a function that takes the DiOTP client as an argument. In production you pass the real client; in tests you pass a fake one. That single choice is what makes the flow testable without sending real messages.
app.js
import express from "express";
import session from "express-session";
import { rateLimit } from "express-rate-limit";
import { DiOTPError, InvalidCodeError, ExpiredError, RateLimitError } from "@diorbit/diotp";
export function createApp(diotp) {
const app = express();
app.set("trust proxy", 1); // only if you run behind exactly one proxy
app.use(express.json());
app.use(session({
secret: process.env.SESSION_SECRET ?? "test-secret",
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production" },
}));
const sendLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
standardHeaders: "draft-7",
legacyHeaders: false,
message: { error: "too_many_requests" },
});
app.post("/api/otp/send", sendLimiter, async (req, res, next) => {
const phone = String(req.body.phone ?? "").replace(/\D/g, "").slice(-10);
if (!/^[6-9]\d{9}$/.test(phone)) return res.status(400).json({ error: "invalid_phone" });
try {
const { requestId, expiresAt } = await diotp.sendOtp({ to: phone, purpose: "login" });
req.session.otp = { requestId, phone };
res.json({ sent: true, expiresAt });
} catch (err) {
if (err instanceof RateLimitError) return res.status(429).json({ error: err.code });
next(err);
}
});
// The verify route and the error handler follow in the next sections.
return app;
}server.js
import { DiOTP } from "@diorbit/diotp";
import { createApp } from "./app.js";
const diotp = new DiOTP({ timeout: 10000, maxRetries: 2 }); // reads DIOTP_API_KEY
createApp(diotp).listen(3000);Two things matter in the send route. The number is cleaned and checked on your server before DiOTP is called, so obvious junk never costs a request. And the request_id goes into req.session, not into the reply. The client never handles it, so nobody can submit a code against a request that belongs to someone else. Rate-limit errors such as resend_cooldown come back as 429 with their code, so the client can show a countdown. The fields are in the send OTP reference.
The verify route: finish the flow safely
Verification is where most mistakes happen: trusting a request_id from the client, signing a user in without a fresh session, or showing a scary error when someone taps the button twice. Add this inside createApp, after the send route.
app.js (verify route and errors)
app.post("/api/otp/verify", async (req, res, next) => {
const pending = req.session.otp;
const code = String(req.body.code ?? "").trim();
if (!pending) return res.status(400).json({ error: "no_pending_code" });
if (!/^\d{4,10}$/.test(code)) return res.status(400).json({ error: "invalid_code" });
try {
await diotp.verifyOtp({ requestId: pending.requestId, code });
} catch (err) {
if (err instanceof InvalidCodeError) return res.status(400).json({ error: "invalid_code" });
if (err instanceof ExpiredError) {
delete req.session.otp;
return res.status(410).json({ error: "expired" });
}
if (err instanceof DiOTPError && err.code === "too_many_attempts") {
delete req.session.otp;
return res.status(429).json({ error: "too_many_attempts" });
}
// A double tap: the first request already verified this code.
if (!(err instanceof DiOTPError) || err.code !== "already_verified") return next(err);
}
delete req.session.otp;
req.session.regenerate((err) => {
if (err) return next(err);
req.session.phone = pending.phone; // the verified number: sign the user in here
res.json({ verified: true });
});
});
// Account and setup problems: log them, show a generic message.
app.use((err, req, res, next) => {
if (!(err instanceof DiOTPError)) return next(err);
console.error("DiOTP error", err.status, err.code);
res.status(503).json({ error: "otp_unavailable" });
});| Outcome | DiOTP status | What your route does |
|---|---|---|
| Verified | 200 | Regenerate the session and sign the user in. |
| invalid_code | 400 | Let the user try again. Each code allows 5 attempts. |
| expired | 410 | Clear the pending request and offer a new code. Codes last 5 minutes. |
| too_many_attempts | 429 | Clear the pending request. The user must ask for a new code. |
| already_verified | 409 | Treat as success: the same code was checked a moment ago. |
| Anything else | Varies | A setup or account problem. Log it and show a generic message. |
Clearing the pending request on expired and too_many_attempts stops the client from retrying a dead request_id. Treating already_verified as success means a double tap on the submit button never shows an error. Every verify code is listed in the verify OTP reference.
Sessions: where the pending code lives
The session is the only place the request_id should live between the two calls. It is tied to an HttpOnly cookie, so scripts on the page cannot read it, and sameSite lax stops other sites from posting to your routes with it.
- Regenerate on success. req.session.regenerate issues a new session id at the moment the user gains access, which closes off session fixation: an attacker who planted a session id before login cannot ride along after it.
- Keep one pending code per session. A new send overwrites req.session.otp, so only the latest code can be verified from that browser.
- Clear it when it can no longer succeed: after success, expiry or too many attempts.
- Use a shared store in production. The default memory store loses everything on restart and does not work across several servers. Use Redis or your database through a compatible express-session store.
- Set secure cookies behind HTTPS. The code above turns secure on when NODE_ENV is production.
A mobile app that cannot keep cookies can use a short-lived signed token in place of the session. The rule stays the same: the server, not the client, decides which request_id a code is checked against.
Rate limits: yours and DiOTP's
DiOTP already enforces limits on every number and key, and a send blocked by those limits is not charged:
| Limit | Value | Error code |
|---|---|---|
| Resend cooldown | One code every 30 seconds per number | resend_cooldown |
| Per number, per hour | 3 codes | phone_hourly_limit |
| Per number, per day | 10 codes | phone_daily_limit |
| Per code | 5 verify attempts, valid for 5 minutes | too_many_attempts, expired |
| Per API key | 30 sends per minute | api_key_minute_limit |
Those limits protect each number. Your own per-IP limit protects your wallet from one script cycling through thousands of different numbers, which is how SMS pumping works. The limiter in app.js allows ten send requests per IP in fifteen minutes; tune it to your traffic.
Behind a proxy, a load balancer or a CDN, set trust proxy to the number of proxies you actually have, so express-rate-limit sees the visitor's real address. Trusting every hop lets an attacker fake the header. On the client, disable the resend button for 30 seconds after each send to match the cooldown. For public sign-up forms, add a bot check as well; our guide to SMS pumping protection covers the wider defence.
Verify webhook signatures in Node
Webhooks tell you when a code was sent, delivered, failed or verified. Add an HTTPS URL under Webhooks in the dashboard and copy the signing secret, which starts with whsec_ and is shown only once. Store it as DIOTP_WEBHOOK_SECRET.
Each delivery carries X-Diorbit-Timestamp, a Unix time in seconds, and X-Diorbit-Signature, the hex HMAC-SHA256 of the timestamp, a dot and the raw body. Hash the body exactly as it arrived. Parsing it to JSON and turning it back into a string can change spacing or key order, and then the signature never matches. That is why this route uses express.raw and must be mounted before express.json.
webhook.js
import express from "express";
import crypto from "node:crypto";
export const webhookRouter = express.Router();
const MAX_AGE_SECONDS = 5 * 60;
webhookRouter.post("/diotp", express.raw({ type: "*/*" }), (req, res) => {
const timestamp = req.get("X-Diorbit-Timestamp") ?? "";
const signature = req.get("X-Diorbit-Signature") ?? "";
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
const age = Math.floor(Date.now() / 1000) - Number(timestamp);
if (!Number.isFinite(age) || Math.abs(age) > MAX_AGE_SECONDS) {
return res.status(400).send("stale timestamp");
}
const expected = crypto
.createHmac("sha256", process.env.DIOTP_WEBHOOK_SECRET)
.update(timestamp + ".")
.update(raw)
.digest();
const given = Buffer.from(signature, "hex");
// timingSafeEqual throws on different lengths, so check that first.
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return res.status(401).send("bad signature");
}
const event = JSON.parse(raw.toString("utf8"));
res.sendStatus(204); // reply fast; do the slow work afterwards
handleEvent(event).catch((err) => console.error("webhook handler failed", err));
});
async function handleEvent(event) {
// event.event is otp.sent, otp.delivered, otp.failed or otp.verified
console.log(event.event, event.request_id, event.channel);
}Mount it in createApp with app.use("/webhooks", webhookRouter) as the first line after creating the app. The timestamp check rejects anything older than five minutes, so a captured delivery cannot be replayed later, and crypto.timingSafeEqual compares in constant time.
Reply with a 2xx within 10 seconds. If you do not, DiOTP retries after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, six attempts in all. Because retries happen, make your handler safe to run twice for the same request_id and event. The webhooks reference lists every header and field.
Test OTP verification in Node.js
Test in two layers. Automated tests check your routes on every commit with a fake DiOTP client, so they cost nothing and need no network. A short manual pass in test mode then checks the real thing end to end.
Automated tests with node:test and supertest
Because createApp takes the client as an argument, a test can pass an object with the same two methods. The helper builds an error that passes the same instanceof checks as a real SDK error. supertest's agent keeps the session cookie between the send and verify calls, just like a browser.
app.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { DiOTPError, InvalidCodeError } from "@diorbit/diotp";
import { createApp } from "./app.js";
// An error that passes the route's instanceof checks, without calling the API.
const apiError = (Type, code, status) => Object.assign(Object.create(Type.prototype), { code, status });
function fakeClient({ correct = "123456" } = {}) {
return {
async sendOtp() {
return { requestId: "req_test_1", expiresAt: new Date(Date.now() + 300000).toISOString() };
},
async verifyOtp({ requestId, code }) {
if (requestId !== "req_test_1") throw apiError(DiOTPError, "not_found", 404);
if (code !== correct) throw apiError(InvalidCodeError, "invalid_code", 400);
return { verified: true };
},
};
}
test("rejects a verify with no pending code", async () => {
const res = await request(createApp(fakeClient())).post("/api/otp/verify").send({ code: "123456" });
assert.equal(res.status, 400);
assert.equal(res.body.error, "no_pending_code");
});
test("a wrong code is refused, the right one signs in", async () => {
const agent = request.agent(createApp(fakeClient()));
await agent.post("/api/otp/send").send({ phone: "9876543210" }).expect(200);
const wrong = await agent.post("/api/otp/verify").send({ code: "000000" });
assert.equal(wrong.body.error, "invalid_code");
const right = await agent.post("/api/otp/verify").send({ code: "123456" });
assert.equal(right.body.verified, true);
});
test("rejects a number that is not a 10-digit mobile", async () => {
const res = await request(createApp(fakeClient())).post("/api/otp/send").send({ phone: "12345" });
assert.equal(res.status, 400);
});Run them with node --test. Add cases for each outcome in the verify table: expired, too_many_attempts and already_verified. Each one is a few lines with apiError.
A manual pass in test mode
A new account starts in test mode with 10 free test messages. They go only to the mobile number you verified at sign-up, so you can run the whole flow without texting anyone else. A send to any other number returns 403 trial_restricted, which also checks that your error handler works.
- Send to your own number and confirm the reply has expiresAt and the session cookie is set.
- Type a wrong code once and check you get invalid_code.
- Tap send twice within 30 seconds and confirm the second call returns resend_cooldown.
- Wait more than 5 minutes before verifying and confirm you get expired.
- Post to the webhook route with a made-up signature and confirm it answers 401.
When the flow works, recharge your wallet to go live: the same key then sends to any Indian mobile number and your code stays as it is. You can go live the same day on DiOTP's shared OTP template without DLT and add your own sender ID later.
A note on TypeScript
The SDK ships its own TypeScript types, so sendOtp and verifyOtp are typed out of the box. Install @types/express and @types/express-session, then extend the session type so req.session.otp is known to the compiler.
session.d.ts
import "express-session";
declare module "express-session" {
interface SessionData {
otp?: { requestId: string; phone: string };
phone?: string;
}
}If you render pages with React or Next.js, the React and Next.js OTP guide builds a front end that talks to routes like these. Mobile teams can follow the React Native and SMS Retriever guide, which uses this backend unchanged. The full API is in the DiOTP docs.
