비트베이크

Building a Secure SMS OTP System in NestJS with Redis in 5 Minutes

2026-04-10T01:01:38.139Z

NESTJS-REDIS-OTP

Stuck on Paperwork Trying to Integrate SMS Verification?

If you're building a side project or startup MVP, you've probably hit this wall: you need SMS phone verification, but legacy API providers require business registration documents, proof of use, and a pre-registered caller ID. This bureaucratic nightmare can waste days before you even write a single line of code.

In this article, we will build a secure and scalable SMS One-Time Password (OTP) system using NestJS, Redis, and EasyAuth—a developer-focused SMS API that requires zero paperwork and lets you start sending messages in exactly 5 minutes.


Solution Overview

Our authentication system will follow this straightforward flow:

  1. The user requests an OTP by providing their phone number.
  2. Our NestJS server generates a 6-digit random code and stores it in Redis with a 3-minute Time-To-Live (TTL).
  3. We trigger the EasyAuth API (POST /send) to instantly dispatch the SMS.
  4. When the user submits the code, we verify it against the value stored in Redis.

> 💡 No Redis? No Problem! > If setting up a Redis instance is too much overhead for your current MVP, EasyAuth provides a built-in POST /verify endpoint. This allows you to achieve completely stateless OTP verification using just two endpoints (/send and /verify) without any database at all!


Step-by-Step Implementation

1. Install Dependencies

We need ioredis to communicate with Redis and axios to make HTTP requests to the EasyAuth API.

npm install ioredis axios

2. Complete Code for AuthService

Here is a production-ready AuthService that handles the entire OTP lifecycle.

import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import Redis from 'ioredis';
import axios from 'axios';

@Injectable()
export class AuthService {
  private redisClient: Redis;
  private readonly EASYAUTH_API_URL = 'https://api.easyauth.co.kr';
  private readonly API_KEY = 'your_easyauth_api_key_here'; // Store this in your .env!

  constructor() {
    // Connects to localhost:6379 by default.
    this.redisClient = new Redis();
  }

  async sendOtp(phoneNumber: string) {
    // 1. Generate a random 6-digit OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    try {
      // 2. Save to Redis with a 3-minute (180s) TTL
      await this.redisClient.set(`otp:${phoneNumber}`, otp, 'EX', 180);

      // 3. Dispatch SMS via EasyAuth
      // Auto-configured caller ID means no pre-registration required!
      await axios.post(`${this.EASYAUTH_API_URL}/send`, {
        to: phoneNumber,
        text: `[MyService] Your verification code is [${otp}].`
      }, {
        headers: {
          'Authorization': `Bearer ${this.API_KEY}`,
          'Content-Type': 'application/json'
        }
      });

      return { message: 'OTP sent successfully.' };
    } catch (error) {
      throw new HttpException('Failed to send SMS.', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async verifyOtp(phoneNumber: string, code: string) {
    // 1. Retrieve OTP from Redis
    const storedOtp = await this.redisClient.get(`otp:${phoneNumber}`);

    if (!storedOtp) {
      throw new HttpException('OTP expired or does not exist.', HttpStatus.BAD_REQUEST);
    }

    // 2. Compare the provided code
    if (storedOtp !== code) {
      throw new HttpException('Invalid OTP code.', HttpStatus.BAD_REQUEST);
    }

    // 3. On success, delete the OTP immediately to prevent reuse
    await this.redisClient.del(`otp:${phoneNumber}`);
    
    return { message: 'Phone number verified successfully.' };
  }
}

3. Controller Setup

import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('send')
  async send(@Body('phoneNumber') phoneNumber: string) {
    return this.authService.sendOtp(phoneNumber);
  }

  @Post('verify')
  async verify(
    @Body('phoneNumber') phoneNumber: string,
    @Body('code') code: string
  ) {
    return this.authService.verifyOtp(phoneNumber, code);
  }
}

Tips & Best Practices

  1. Prevent SMS Bombing (Rate Limiting) Malicious bots might spam your /send endpoint, driving up your SMS costs. Since you already have Redis, it's highly recommended to implement rate limiting. Restrict OTP requests to a maximum of 1 request per minute per phone number or IP address.

  2. Immediate OTP Invalidation Always delete the OTP from Redis (this.redisClient.del()) immediately after a successful verification. This mitigates replay attacks where an attacker attempts to reuse a valid code before its TTL expires.


Conclusion

By pairing NestJS with Redis's excellent TTL features, you can build a robust custom OTP system with full control over the verification flow.

More importantly, as a solo developer or startup, you shouldn't waste your precious time on bureaucracy. Skip the paperwork and the legacy carriers. With [EasyAuth], you get an ultra-simple API, auto-configured caller IDs, and competitive pricing at just 15~25 KRW per message (half the price of traditional services).

Sign up today and get 10 free SMS credits to start building your MVP in 5 minutes!

비트베이크에서 광고를 시작해보세요

광고 문의하기

다른 글 보기

2026-08-06T06:01:33.120Z

2026 GTX 개통 임박! A/B/C 노선 수혜지역 투자 가이드

2026년 GTX A/B/C 노선 개통이 임박하며 수도권 부동산 시장이 들썩이고 있습니다. GTX 노선별 개통 현황과 함께, 주요 수혜지역을 심층 분석하고 실거주 및 투자를 위한 현명한 전략과 유의점을 제시하여 성공적인 아파트 투자를 돕는 가이드입니다.

2026-08-05T06:01:33.825Z

2026 하반기 재건축 투자: 규제 완화 속 핵심 전략

2026년 하반기, 규제 완화 기대감 속 재건축 투자의 핵심 전략을 알아봅니다. 정부 정책 변화 분석, 유망 지역 선정 기준, 주의할 점, 그리고 성공적인 투자를 위한 전문가들의 조언까지, 2026 부동산 시장에서 기회를 잡을 방법을 제시합니다.

2026-08-04T06:01:37.246Z

2026 하반기 청약, 대출 금리 변화 활용 내집마련 필승 전략

2026년 하반기 청약 시장은 변화하는 대출 금리와 정책, 지역별 수급 상황에 따라 기회와 도전이 공존합니다. 이 글에서는 부동산 시장 동향과 주택담보대출 전략, 인기 청약 단지 분석, 청약 가점 및 특별공급 활용 팁 등 내 집 마련을 위한 필승 전략을 제시합니다. 철저한 준비와 현명한 판단으로 2026년 내 집 마련의 꿈을 이루세요.

2026-08-04T01:01:36.795Z

2026년 청약 성공 전략: 무주택자 내집마련 필승 가이드

2026년 무주택자의 내집마련 꿈을 위한 필승 청약 전략 가이드입니다. 청약 가점부터 특별공급 활용법, 현명한 대출 전략, 유망 단지 분석, 그리고 제도 변화까지 2026년 청약 성공을 위한 모든 정보를 담았습니다.

서비스

피드자주 묻는 질문고객센터

문의

비트베이크

레임스튜디오 | 사업자 등록번호 : 542-40-01042

경기도 남양주시 와부읍 수례로 116번길 16, 4층 402-제이270호

트위터인스타그램네이버 블로그