AI summary

Add an SMS one-time code after password login in Express with Twilio Verify: send it, check it, protect routes and add rate limits.

  • You don't generate or store the code. Twilio Verify generates, sends and checks it.
  • Checking a code that has expired or was already used returns a 404, and you have to catch it.
  • SMS costs money. Add your own rate limits on top of Twilio's.

A correct password doesn’t tell you the person typing it owns the phone on the account. A one-time code over SMS (OTP) adds that second check.

You don’t have to build much for it. Twilio Verify generates the code, sends it and checks it. Twilio keeps a record of each code it sends, called a verification. A verification is pending until the user types the right code, and then it’s approved.

Your app stores one flag, verified, in the session. The session is the data the server holds for one logged-in browser, and a cookie tells the server which session belongs to which browser. Your app also handles Twilio’s answers and limits how many SMS messages people can trigger, because you pay for each one.

I built this in 2022 as a small demo with Express, EJS, MongoDB, Passport and Twilio Verify. That demo used the library versions of that time. I’ve rewritten the pieces below for today’s Twilio SDK, Express 5, Mongoose and Passport, so they don’t match the 2022 code line for line.

OTP flow from login to dashboardStep through it, or press play.
  1. Password check

    passport-local finds the user by email and compares the password with bcrypt.

  2. Half a session

    The session exists, but verified is false. The user can reach /users/verify, not the dashboard.

    req.session.verified = false
  3. SMS sent

    Twilio generates and sends the code. The verification starts as pending.

    verifications.create({ to, channel: 'sms' })
  4. Code entry

    The user types the code from the SMS into the form. It's valid for 10 minutes by default.

  5. Code check

    The server asks Twilio about the code. If it's right, the status comes back approved.

    verificationChecks.create({ to, code })
  6. Full session

    The session gets flagged and the protected routes open up.

    req.session.verified = true

Sending and checking the code

In the Twilio Console, create a Verify Service. You need only one, not one per code. It holds the settings your codes go out with, such as the name shown in the SMS. Put its SID, the one starting with VA, in your .env.

Each verification stays open for 10 minutes by default. After that, its code no longer works.

Twilio’s current examples authenticate with an API key. Store phone numbers in E.164 format (+1...). In the demo I used intl-tel-input on the signup form for that.

js
// config/twilio.js
const twilio = require("twilio");

const client = twilio(process.env.TWILIO_API_KEY, process.env.TWILIO_API_SECRET, {
  accountSid: process.env.TWILIO_ACCOUNT_SID,
});
const verify = client.verify.v2.services(process.env.TWILIO_VERIFY_SERVICE_SID);

function sendCode(phone) {
  return verify.verifications.create({ to: phone, channel: "sms" });
}

async function checkCode(phone, code) {
  try {
    const check = await verify.verificationChecks.create({ to: phone, code });
    return check.status === "approved" ? "approved" : "wrong";
  } catch (err) {
    if (err.status === 404) return "expired";
    if (err.code === 60202) return "locked";
    throw err;
  }
}

module.exports = { sendCode, checkCode };

The catch block matters. My first version, on Express 4, didn’t catch Twilio’s errors. An expired code comes back as a 404, which the SDK throws as an error. With nothing to catch it, Node’s default settings stop the whole process.

What a code check can returnPick a case to see Twilio's answer and what the app should do.

Right code

Twilio deletes the verification, so the same code can't be used twice.

  • status: approved (added)
  • req.session.verified = true (added)
  • Redirect to /users/dashboard

Wrong code

Nothing is thrown. Don't treat a returned response as success.

  • status: pending
  • verified stays false
  • Ask for the code again

10 minutes passed

10 minutes is the default. The API can't change it; Twilio Support can set a different window per service.

  • HTTP 404 (changed)
  • The verification no longer exists (changed)
  • Request a new code

5 wrong attempts

Each verification gets 5 checks. You may also see a 404 after that.

  • HTTP 429, error code 60202 (changed)
  • Wait it out, then start a new verification

Protecting the routes

The app uses four middleware functions: isLoggedIn, isVerified, notLoggedIn and notVerified. Middleware is a function Express runs before a route’s own handler. Each one either calls next() to move on or answers the request itself, here with a redirect.

isLoggedIn checks the password step and isVerified checks the code step. notLoggedIn and notVerified do the opposite. Put isLoggedIn and isVerified on every route you want to protect. The code below shows the first two.

js
// config/middleware.js
const isLoggedIn = (req, res, next) =>
  req.user ? next() : res.redirect("/users/login");

const isVerified = (req, res, next) =>
  req.session.verified ? next() : res.redirect("/users/verify");
js
// routes/user.js
const messages = {
  wrong: "That code is wrong.",
  expired: "That code has expired. Request a new one.",
  locked: "Too many attempts. Wait a bit and try again.",
};

router.post(
  "/login",
  notLoggedIn,
  loginLimiter,
  passport.authenticate("local", {
    failureRedirect: "/users/login",
    failureFlash: true,
  }),
  async (req, res) => {
    // Passport has already regenerated the session at this point.
    req.session.verified = false;
    await sendCode(req.user.phonenumber);
    res.redirect("/users/verify");
  },
);

router.post("/verify", isLoggedIn, notVerified, verifyLimiter, async (req, res) => {
  const result = await checkCode(req.user.phonenumber, req.body.verifyCode);
  if (result === "approved") {
    req.session.verified = true;
    return res.redirect("/users/dashboard");
  }
  req.flash("error_msg", messages[result]);
  res.redirect("/users/verify");
});

router.post("/resend", isLoggedIn, notVerified, resendLimiter, async (req, res) => {
  await sendCode(req.user.phonenumber);
  res.redirect("/users/verify");
});

router.get("/dashboard", isLoggedIn, isVerified, (req, res) => {
  res.render("dashboard");
});

In the demo, resend was a GET link. I’ve made it a POST, because a GET that sends an SMS can be triggered by a link preview or a request from another site.

In Express 5, errors in async handlers reach the error middleware on their own. That’s the middleware Express calls when a handler fails. On Express 4 you’d need try/catch and next(err).

Rate limits and SMS pumping

Twilio protects a single number on its own: 5 checks per verification and a cap on repeated sends.

Resending within the 10 minutes delivers the same code. Twilio recommends at most one send per 30 seconds per number, and the resend limit below uses the same window.

None of those limits help if someone feeds your app a long list of different numbers. Every SMS still lands on your bill. The numbers belong to the attacker or their partners, who get a cut of what the mobile carriers charge for each SMS. That attack is called SMS pumping, so add rate limits of your own:

js
const { rateLimit } = require("express-rate-limit");

const perUser = (windowMs, limit) =>
  rateLimit({
    windowMs,
    limit,
    keyGenerator: (req) => req.user.id,
    standardHeaders: "draft-8",
    legacyHeaders: false,
  });

const loginLimiter = rateLimit({ windowMs: 15 * 60_000, limit: 10 });
const resendLimiter = perUser(30_000, 1);
const verifyLimiter = perUser(60_000, 5);

Those numbers are a starting point, so tune them to your traffic.

By default the limiter keeps its counts in the server’s memory. If you run more than one server, each one counts on its own, so move the counts to a shared store like Redis.

There are three settings on Twilio’s side too. The first is Service Rate Limits, where you define a key and a bucket.

The key is what Twilio counts by, such as the user’s IP address, and you choose its name. The bucket is how many sends that key gets in a time window.

If you named the key end_user_ip_address, you pass rateLimits: { end_user_ip_address: req.ip } when sending. req.ip is the visitor’s IP address as Express sees it.

The other two are quick: turn on SMS Fraud Guard, and use Geo Permissions to switch off countries where you have no users.

Before going live

The demo skipped most of this:

  • Session store: express-session’s default MemoryStore leaks memory and only works in a single process. Keep sessions in a database instead, for example Redis or MongoDB, through a store package such as connect-redis or connect-mongo.
  • Cookies: Keep httpOnly on so page scripts can’t read the session cookie; express-session sets it by default. Set sameSite: "lax" yourself, so the browser leaves the cookie off most requests that other sites start. In production, also set secure, so the cookie only goes over HTTPS.
  • Proxies: In production the app often sits behind a proxy, such as nginx or a load balancer, that receives each request first and passes it on. Add app.set("trust proxy", 1) so Express reads the visitor’s address and HTTPS status from the proxy’s headers. Without it, the secure cookie won’t be set and req.ip will be the proxy’s address.
  • CSRF: The forms POST and rely on the session cookie, so another site could make a logged-in user’s browser submit them. That attack is called CSRF. Add a CSRF token, a random value your own forms send and other sites can’t know.
  • Passwords: Hash with bcrypt and put if (!this.isModified("password")) return; in the pre("save") hook, which Mongoose runs before it saves a user, or each save hashes the hash.
  • Signup: Don’t hand req.body straight to User.create, because a user can post extra fields you never meant to accept. Pick the fields one by one.
  • If you update older code like the 2022 demo: Mongoose 7 dropped the findById callback, so use await in deserializeUser, the Passport function that loads the user from the session on each request. Express 5 removed res.redirect("back"), so use req.get("Referrer") || "/".

If MongoDB runs on the same server, don’t expose its port. Securing MongoDB with UFW shows how to close it with Ubuntu’s firewall.

If your app runs on Next.js with NextAuth.js, why jwt.verify can’t read its session token covers how to read the session instead.

References

  1. Twilio Verify API
  2. Twilio Verification Check resource
  3. Twilio Verify developer best practices
  4. Twilio Verify Service Rate Limits
  5. Twilio Verify rate limits and timeouts
  6. Twilio guidance on SMS pumping and toll fraud
  7. Express security best practices
  8. express-session documentation
  9. Passport changelog
  10. Migrating to Express 5
  11. Migrating to Mongoose 7
  12. express-rate-limit configuration

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.