Implementing SMS Verification Codes with MongoDB TTL in a Backend Service

This article explains how to build a basic SMS verification feature by choosing a gateway, generating and storing 4‑digit codes in MongoDB with TTL, and validating them through a simple backend workflow using Node.js and Mongoose.

System Architect Go
System Architect Go
System Architect Go
Implementing SMS Verification Codes with MongoDB TTL in a Backend Service

SMS verification codes are a fundamental feature for most apps, and this guide walks through a straightforward implementation.

Two types of SMS gateway platforms exist: one where the developer generates and validates the code, and another where the platform handles both generation and validation. The guide focuses on the former.

Code storage can be done either in server‑side sessions or in a database. Sessions are simple but volatile, while databases provide persistence and can automatically expire records using TTL (time‑to‑live) features.

MongoDB is chosen for storage because it natively supports TTL indexes, eliminating the need for an additional Redis cache in projects already using MongoDB.

The server‑side workflow includes:

Receiving the user's phone number and validating its format (e.g., using a regular expression like /^1\d{10}$/ for a simple 11‑digit number starting with 1).

Generating a random 4‑digit verification code (e.g., using Math.random()).

Calling the SMS provider's API to send the code to the user's phone.

Saving the phone number, code, and an expiration time in MongoDB with a TTL index defined in the Mongoose schema.

When the user submits the code, querying MongoDB to confirm a matching phone‑code pair exists and is still valid.

The Mongoose schema must include a Date field with an index and an expires option to enforce the TTL; the operation uses findOneAndUpdate to upsert records.

After these steps, the SMS verification feature is complete.

The article concludes without further commentary.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Node.jsTTLAPIMongoDBSMS VerificationMongoose
System Architect Go
Written by

System Architect Go

Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.