비트베이크

Implementing SMS Authentication with Better Auth in Next.js 15: 2026 Complete Guide

2026-03-24T01:03:35.086Z

BETTER-AUTH-SMS

Implementing SMS Authentication with Better Auth in Next.js 15: 2026 Complete Guide

You wanted to add SMS verification to your side project. Then you found out the provider needs business registration documents, a pre-registered sender number, and a three-day approval process. Sound familiar?

In this guide, we'll build a complete SMS OTP authentication system from scratch using Better Auth's Phone Number plugin and Next.js 15 App Router — with real, working code you can copy and adapt today.

What You'll Learn

  • Setting up Better Auth with Next.js 15 App Router
  • Configuring the Phone Number plugin for OTP-based auth
  • Connecting a custom SMS delivery provider
  • Building the OTP send/verify UI in React
  • Security best practices for production

Step 1: Project Setup

Install Better Auth

npx create-next-app@latest my-auth-app --app --typescript
cd my-auth-app
npm install better-auth

Environment Variables

Create a .env.local file:

BETTER_AUTH_SECRET=your-secret-key-at-least-32-characters-long
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=file:./dev.db
SMS_API_KEY=your-sms-api-key

The BETTER_AUTH_SECRET must be at least 32 characters. Generate one with openssl rand -base64 32.


Step 2: Server-Side Auth Configuration

Create your auth instance in lib/auth.ts:

// lib/auth.ts
import { betterAuth } from "better-auth";
import { phoneNumber } from "better-auth/plugins";
import Database from "better-sqlite3";

export const auth = betterAuth({
  database: new Database("./sqlite.db"),
  plugins: [
    phoneNumber({
      otpLength: 6,
      expiresIn: 300, // 5 minutes
      allowedAttempts: 3,
      sendOTP: async ({ phoneNumber, code }, ctx) => {
        // Send OTP via your SMS provider
        await fetch("https://api.easyauth.kr/v1/send", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${process.env.SMS_API_KEY}`,
          },
          body: JSON.stringify({
            phoneNumber,
            code,
          }),
        });
        // Note: Better Auth docs recommend NOT awaiting sendOTP
        // to prevent timing attacks and speed up responses
      },
      signUpOnVerification: {
        getTempEmail: (phoneNumber) => `${phoneNumber}@phone.local`,
        getTempName: (phoneNumber) => phoneNumber,
      },
    }),
  ],
});

Key Configuration Options

| Option | Default | Description | |--------|---------|-------------| | otpLength | 6 | Number of digits in the OTP code | | expiresIn | 300 | OTP expiration in seconds | | allowedAttempts | 3 | Failed attempts before OTP is invalidated | | signUpOnVerification | — | Auto-create user accounts on first verification | | phoneNumberValidator | — | Custom validation function for phone numbers | | verifyOTP | — | Custom verification logic (for external providers) |

Connect the Next.js Route Handler

// app/api/auth/[...all]/route.ts
import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/lib/auth";

export const { POST, GET } = toNextJsHandler(auth);

This single catch-all route handler exposes all Better Auth endpoints under /api/auth/*.

Run Database Migration

npx auth migrate

This automatically adds phoneNumber (string) and phoneNumberVerified (boolean) columns to your user table.


Step 3: Client Configuration

// lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
import { phoneNumberClient } from "better-auth/client/plugins";

export const authClient = createAuthClient({
  plugins: [phoneNumberClient()],
});

The phoneNumberClient plugin adds two methods to your client:

  • authClient.phoneNumber.sendOtp() — triggers OTP delivery
  • authClient.phoneNumber.verify() — validates the code and creates a session

Step 4: Build the SMS Auth UI

// app/components/PhoneAuth.tsx
"use client";

import { useState } from "react";
import { authClient } from "@/lib/auth-client";

export default function PhoneAuth() {
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"phone" | "verify">("phone");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSendOTP = async () => {
    setLoading(true);
    setError("");
    try {
      await authClient.phoneNumber.sendOtp({
        phoneNumber: phone,
      });
      setStep("verify");
    } catch (e) {
      setError("Failed to send OTP. Please check the number and try again.");
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async () => {
    setLoading(true);
    setError("");
    try {
      await authClient.phoneNumber.verify({
        phoneNumber: phone,
        code,
      });
      // Verification successful — session is now active
      window.location.href = "/dashboard";
    } catch (e) {
      setError("Invalid code. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>Phone Verification</h1>

      {step === "phone" ? (
        <div>
           setPhone(e.target.value)}
            className="w-full p-3 border rounded-lg"
          /&gt;
          
            {loading ? "Sending..." : "Send Verification Code"}
          
        </div>
      ) : (
        <div>
          <p>
            Enter the 6-digit code sent to {phone}
          </p>
           setCode(e.target.value)}
            className="w-full p-3 border rounded-lg text-center text-2xl tracking-widest"
          /&gt;
          
            {loading ? "Verifying..." : "Verify"}
          
           { setStep("phone"); setCode(""); }}
            className="w-full p-3 text-gray-500 text-sm"
          &gt;
            Use a different number
          
        </div>
      )}

      {error &amp;&amp; <p>{error}</p>}
    </div>
  );
}

Step 5: Session Check in Server Components

One of the biggest advantages of Better Auth with Next.js 15 is seamless server-side session access:

// app/dashboard/page.tsx
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";

export default async function Dashboard() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) redirect("/login");

  return (
    <div>
      <h1>Welcome!</h1>
      <p>Phone: {session.user.phoneNumber}</p>
      <p>Verified: {session.user.phoneNumberVerified ? "Yes" : "No"}</p>
    </div>
  );
}

Step 6: Password Reset via Phone (Optional)

Better Auth's phone plugin also supports password reset flows via SMS:

// Request a password reset OTP
await authClient.phoneNumber.requestPasswordReset({
  phoneNumber: "+1234567890",
});

// Reset the password with the OTP
await authClient.phoneNumber.resetPassword({
  phoneNumber: "+1234567890",
  otp: "123456",
  newPassword: "newSecurePassword",
});

This gives users an alternative recovery path when they've lost access to their email.


Security Best Practices

1. Rate Limiting

Better Auth provides built-in brute force protection. When allowedAttempts is exceeded, the OTP is automatically deleted and a 403 response is returned. The user must request a new code.

For additional protection, consider adding application-level rate limiting on the /api/auth/* routes:

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const rateLimitMap = new Map();

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith("/api/auth")) {
    const ip = request.headers.get("x-forwarded-for") ?? "unknown";
    const now = Date.now();
    const windowMs = 60_000; // 1 minute
    const maxRequests = 10;

    const entry = rateLimitMap.get(ip);
    if (entry &amp;&amp; now - entry.timestamp &lt; windowMs) {
      if (entry.count &gt;= maxRequests) {
        return NextResponse.json(
          { error: "Too many requests" },
          { status: 429 }
        );
      }
      entry.count++;
    } else {
      rateLimitMap.set(ip, { count: 1, timestamp: now });
    }
  }

  return NextResponse.next();
}

> Note: For production, use a Redis-backed rate limiter instead of an in-memory Map.

2. Phone Number Validation

Always validate phone numbers server-side before sending OTPs:

phoneNumber({
  phoneNumberValidator: (phoneNumber) =&gt; {
    // E.164 format validation
    return /^\+[1-9]\d{1,14}$/.test(phoneNumber);
  },
})

3. Timing Attack Prevention

As recommended by the Better Auth documentation, avoid awaiting the sendOTP function. This ensures consistent response times regardless of whether the phone number exists in your system, preventing attackers from enumerating valid numbers.

4. OTP Expiration

Keep expiresIn short (300 seconds or less). Longer windows increase the risk of interception.


Choosing an SMS Provider

The biggest friction point in SMS authentication isn't the code — it's the provider setup. Most SMS services require business registration, sender number pre-registration, compliance documents, and days of approval time.

For side projects, MVPs, and indie apps, this overhead kills momentum. Services like EasyAuth remove that barrier entirely — no documents required, API keys issued instantly on signup, and pricing starts at just 15-25 KRW per message (roughly $0.01-0.02 USD). They also offer 10 free messages to get started. Simply drop the API call into your sendOTP callback and your entire auth flow is live.


Project Structure Overview

my-auth-app/
├── app/
│   ├── api/auth/[...all]/route.ts   # Better Auth route handler
│   ├── components/PhoneAuth.tsx       # OTP UI component
│   ├── dashboard/page.tsx             # Protected page
│   ├── login/page.tsx                 # Login page
│   └── layout.tsx
├── lib/
│   ├── auth.ts                        # Server auth config
│   └── auth-client.ts                 # Client auth config
├── middleware.ts                       # Rate limiting
├── .env.local
└── package.json

Wrapping Up

Better Auth's Phone Number plugin handles the heavy lifting of OTP authentication — code generation, expiration, brute force protection, session creation — all behind a single sendOTP callback. Combined with Next.js 15's App Router, you get server-side session checks in React Server Components and a clean client-side API for sending and verifying codes.

The entire implementation is around 100 lines of actual code across 4-5 files. The hardest part used to be finding an SMS provider that doesn't require a week of paperwork. With no-friction services like EasyAuth, you can go from npx create-next-app to a fully working SMS auth system in under 30 minutes.

Build fast, validate fast. 🚀

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

광고 문의하기

다른 글 보기

2026-08-08T06:01:29.764Z

손님 부르는 중개사 블로그, 상위노출 키워드 전략: 우리 사무소로 고객을 이끄는 비법!

부동산 중개사님을 위한 블로그 상위노출 키워드 전략! 우리 동네 잠재 고객을 사로잡고, 매물 정보에 키워드를 자연스럽게 녹이는 노하우를 공개합니다. 손님 유입을 늘리고 사무소 경쟁력을 높이는 중개사 마케팅 비법을 지금 바로 확인하세요.

2026-08-08T01:01:10.100Z

변동성 시장, 중개사가 고객 신뢰 얻는 지역 동향 브리핑 노하우

변동성 시장에서 부동산 중개사가 고객 신뢰를 얻는 핵심은 심도 있는 지역 시장 분석과 맞춤형 브리핑입니다. 공신력 있는 데이터를 활용하여 지역 동향을 해석하고, 고객의 눈높이에 맞춰 복잡한 정보를 명확하게 전달하는 노하우를 통해 중개사는 경쟁력을 강화하고 시장 변동성 속 기회를 창출할 수 있습니다.

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 부동산 시장에서 기회를 잡을 방법을 제시합니다.

서비스

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

문의

비트베이크

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

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

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