비트베이크

[Auth.js v5] Implementing SMS OTP Authentication in Next.js in 5 Minutes (Zero Paperwork)

2026-04-28T01:02:47.888Z

developer authentication modern

Must SMS Authentication Be This Complicated?

If you are developing a side project or a startup MVP, you will eventually hit a wall where you need "Phone Number Verification." However, integrating standard telecom APIs or major platforms is often a nightmare of administrative red tape rather than actual development. You are typically asked to:

  • Submit a business registration certificate (What if you're a student or solo dev?).
  • Pre-register a verified sender ID.
  • Wait 3 to 5 business days for approval.

This breaks a developer's flow. Today, we will look at how to implement SMS OTP authentication in just 5 minutes using the recently stabilized Auth.js v5 (formerly NextAuth) in a Next.js App Router environment, powered by EasyAuth—an API that requires zero paperwork.


Why Auth.js v5 + EasyAuth?

  1. Auth.js v5: Fully compatible with the modern Next.js App Router and Edge environments. By using the Credentials provider, integrating custom OTP flows becomes incredibly easy.
  2. EasyAuth:
    • Zero Paperwork: No business registration or usage certificates required.
    • Instant Setup: Start sending messages within 5 minutes of signing up (10 free trials included).
    • Automatic Sender ID: Send SMS immediately without the hassle of pre-registering a caller ID.
    • Simple API Structure: Just two endpoints—/send and /verify.

Step 1: Configuring Auth.js v5

First, install the latest beta version of Auth.js in your Next.js project.

npm install next-auth@beta

Create an auth.ts file in the root of your project (or inside src). Here, we will link EasyAuth's /verify API inside the authorize callback.

import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Credentials({
      name: "SMS OTP",
      credentials: {
        phone: { label: "Phone Number", type: "text" },
        code: { label: "OTP Code", type: "text" },
      },
      async authorize(credentials) {
        if (!credentials?.phone || !credentials?.code) return null;

        // Verify the OTP via EasyAuth API
        const response = await fetch("https://api.easyauth.kr/verify", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${process.env.EASYAUTH_API_KEY}`
          },
          body: JSON.stringify({
            phone: credentials.phone,
            code: credentials.code
          })
        });

        const data = await response.json();

        // Return user session object if verification succeeds
        if (response.ok && data.success) {
          return { id: String(credentials.phone), name: String(credentials.phone) };
        }

        return null; // Return null on failure
      }
    })
  ],
  pages: {
    signIn: "/login", // Custom login page route
  }
});

Step 2: Creating the OTP Send API (Route Handler)

Exposing API keys directly on the client side is a major security risk. Let's create a Next.js Route Handler to call EasyAuth's /send endpoint securely from the server.

Create a file at app/api/send-otp/route.ts.

import { NextResponse } from "next/server";

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

    // Send OTP via EasyAuth API
    const response = await fetch("https://api.easyauth.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: "OTP sent" });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: "Internal Server Error" }, 
      { status: 500 }
    );
  }
}

Step 3: Implementing the Client Login Form

Finally, build the UI where users can input their phone numbers, request a code, and submit it to log in.

app/login/page.tsx

"use client";

import { useState } from "react";
import { signIn } from "next-auth/react";

export default function LoginPage() {
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<1 | 2>(1);

  // 1. Request OTP
  const handleSendCode = async () => {
    const res = await fetch("/api/send-otp", {
      method: "POST",
      body: JSON.stringify({ phone }),
    });
    
    if (res.ok) {
      alert("OTP has been sent!");
      setStep(2);
    } else {
      alert("Failed to send OTP. Please try again.");
    }
  };

  // 2. Verify OTP & Process NextAuth Login
  const handleVerifyCode = async () => {
    const result = await signIn("credentials", {
      phone,
      code,
      redirect: true,
      redirectTo: "/dashboard", // Route to redirect after successful login
    });
  };

  return (
    <div>
      <h1>SMS Authentication</h1>
      
      {step === 1 ? (
        <div>
           setPhone(e.target.value)} 
            placeholder="Phone Number (e.g. 01012345678)" 
            className="border p-3 rounded"
          /&gt;
          
            Send Code
          
        </div>
      ) : (
        <div>
           setCode(e.target.value)} 
            placeholder="6-digit OTP" 
            className="border p-3 rounded"
          /&gt;
          
            Verify &amp; Login
          
        </div>
      )}
    </div>
  );
}

💡 Tips & Best Practices

  • Strict Environment Variables: Make sure EASYAUTH_API_KEY is strictly kept in .env.local for server-side use only. Never add the NEXT_PUBLIC_ prefix, as it will leak your key to the browser!
  • Robust Error Handling: In a production environment, add regex validation for phone numbers and provide clear feedback if the OTP is incorrect or expired.

Conclusion: The Easiest Way to Authenticate

We’ve explored how to cleanly implement an SMS OTP system using Next.js App Router and Auth.js v5.

While traditional methods would leave you stuck in administrative limbo for days just waiting for approvals, EasyAuth empowers you to bypass all the paperwork and finish your core business logic in just 5 minutes. If you are a solo developer, freelancer, or startup rushing to launch an MVP without the enterprise hassle, sign up for EasyAuth today and test the code above with your 10 free credits!

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

광고 문의하기

다른 글 보기

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호

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