비트베이크

Implementing SMS Authentication in Next.js App Router in 10 Minutes (No Paperwork)

2026-04-13T01:03:05.930Z

NEXTJS-SMS-AUTH

Implementing SMS Authentication in Next.js App Router in 10 Minutes (No Paperwork)

One of the most common features you need when building a side project or a startup MVP is SMS Authentication (OTP). However, when you actually try to integrate an SMS API, you often hit a massive wall of bureaucracy.

“Please submit your business registration.” “We need a telecommunications service certificate.” “You must pre-register a sender ID.”

For a solo developer or an early-stage founder trying to launch an MVP over the weekend, this kind of paperwork is a huge waste of time.

In this tutorial, we will learn how to implement a fully functional SMS authentication system in just 10 minutes using Next.js App Router and EasyAuth—a developer-friendly API that requires zero paperwork and can be set up in 5 minutes.


Why EasyAuth + Next.js App Router?

The Next.js App Router allows seamless integration between server-side logic (Route Handlers) and Client Components, enabling rapid development while keeping your API keys perfectly secure.

By combining this with EasyAuth, you get the following benefits:

  • Zero Paperwork: Get your API key instantly without submitting business licenses or certificates.
  • Auto Sender ID: No tedious pre-registration process for the sender's phone number.
  • Highly Affordable: Costs only 15~25 KRW per message, about half the price of traditional providers (30~50 KRW).
  • Extremely Simple: Built around just two clean endpoints: POST /send and POST /verify.

Let's dive into the code.

Step 1: Environment Setup

First, sign up on the EasyAuth dashboard, grab your API key, and add it to your project's .env.local file.

EASYAUTH_API_KEY=your_easyauth_api_key_here

Step 2: Creating API Route Handlers

If you call the EasyAuth API directly from the client, your API key will be exposed. To prevent this, we'll create backend routes using Next.js Route Handlers to proxy our requests securely.

1. Send OTP Route (app/api/send-sms/route.ts)

import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const { phone } = await request.json();

    const response = await fetch('https://api.easyauth.co.kr/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.EASYAUTH_API_KEY}`,
      },
      body: JSON.stringify({ phone }),
    });

    if (!response.ok) throw new Error('Failed to send');

    return NextResponse.json({ success: true, message: 'Verification code sent.' });
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Error occurred while sending SMS.' }, { status: 500 });
  }
}

2. Verify OTP Route (app/api/verify-sms/route.ts)

import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const { phone, code } = await request.json();

    const response = await fetch('https://api.easyauth.co.kr/verify', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.EASYAUTH_API_KEY}`,
      },
      body: JSON.stringify({ phone, code }),
    });

    const data = await response.json();

    if (!data.success) {
      return NextResponse.json({ success: false, error: 'Invalid verification code.' }, { status: 400 });
    }

    return NextResponse.json({ success: true, message: 'Verification successful.' });
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Error processing verification.' }, { status: 500 });
  }
}

Step 3: Implementing the Client Component (Complete Code)

Now, let's create the UI component where users will input their phone number and the OTP code. Create a file at app/components/SmsAuth.tsx and paste the following code.

'use client';

import { useState } from 'react';

export default function SmsAuth() {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [step, setStep] = useState<'SEND' | 'VERIFY'>('SEND');
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState('');

  const handleSendSms = async () => {
    setIsLoading(true);
    setMessage('');
    
    try {
      const res = await fetch('/api/send-sms', {
        method: 'POST',
        body: JSON.stringify({ phone }),
      });
      const data = await res.json();
      
      if (data.success) {
        setStep('VERIFY');
        setMessage('Verification code sent. Please enter it within 3 minutes.');
      } else {
        setMessage(data.error);
      }
    } catch (err) {
      setMessage('A network error occurred.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    setIsLoading(true);
    setMessage('');
    
    try {
      const res = await fetch('/api/verify-sms', {
        method: 'POST',
        body: JSON.stringify({ phone, code }),
      });
      const data = await res.json();
      
      if (data.success) {
        setMessage('✅ Phone verification complete!');
        // TODO: Proceed to the next step (e.g., signup completion)
      } else {
        setMessage('❌ ' + data.error);
      }
    } catch (err) {
      setMessage('A network error occurred.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <h2>Phone Verification</h2>
      
      <div>
        <div>
          Phone Number
          <div>
             setPhone(e.target.value)}
              placeholder='e.g. 01012345678'
              disabled={step === 'VERIFY'}
              className='flex-1 px-4 py-2 border rounded-md focus:ring-2 focus:ring-blue-500 outline-none'
            /&gt;
            
              {step === 'VERIFY' ? 'Resend' : 'Send Code'}
            
          </div>
        </div>

        {step === 'VERIFY' &amp;&amp; (
          <div>
            Verification Code
            <div>
               setCode(e.target.value)}
                placeholder='Enter 6-digit code'
                className='flex-1 px-4 py-2 border rounded-md focus:ring-2 focus:ring-blue-500 outline-none'
              /&gt;
              
                Verify
              
            </div>
          </div>
        )}

        {message &amp;&amp; (
          <p>
            {message}
          </p>
        )}
      </div>
    </div>
  );
}

Tips & Best Practices for Production

  1. API Key Security (Golden Rule) Never call the EasyAuth API directly from a Client Component ('use client'). Doing so exposes your secret API key in the browser's network tab. Always proxy the request through Next.js Route Handlers or Server Actions as shown above.
  2. Implement Rate Limiting To prevent malicious users from abusing your SMS endpoint and draining your credits, implement IP-based rate limiting on your server side. Tools like Upstash Redis make this very easy.
  3. Enhance UX with a Timer In a real-world application, it is highly recommended to display a 3-minute (180 seconds) countdown timer using setInterval once the SMS has been sent.

Conclusion

We just built a secure, fully functional SMS authentication flow in Next.js App Router using EasyAuth, without submitting a single piece of paperwork. The whole process, from setup to coding, takes less than 10 minutes.

Are you building a toy project, a startup MVP, or an e-commerce platform where speed is everything? Sign up for [EasyAuth] today, claim your 10 free test credits, and try this code out immediately! Stop wasting your precious weekends struggling with outdated SMS API providers.

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

광고 문의하기

다른 글 보기

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호

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