Đăng nhập bằng OTP số điện thoại qua KakaoTalk trong Next.js (App Router)

The K-OTP team
25 thg 10, 2026

Hướng dẫn này xây dựng luồng đăng nhập bằng OTP số điện thoại cho một ứng dụng Next.js App Router: người dùng nhập số di động, nhận mã 6 chữ số trên KakaoTalk, nhập mã và được đăng nhập. Máy chủ của bạn giữ khóa bí mật và giao tiếp với K-OTP từ Server Actions, nên trình duyệt không bao giờ thấy khóa và backend của bạn có thể tin cậy kết quả.

Bạn có thể xây dựng và kiểm thử toàn bộ với khóa thử nghiệm: không có gì được gửi và không tốn credit.

Bạn cần gì

  • Một ứng dụng Next.js 15 trở lên dùng App Router (các mẫu mã đã được kiểm tra kiểu với Next.js 16).
  • Một tài khoản K-OTP. Trên console, mở ứng dụng của bạn, vào API keys, chuyển sang tab Test và tạo khóa thử nghiệm. Dùng khóa bí mật sk_test_.
  • @k-otp/sdk 2.1.0 và server-only:
npm install @k-otp/sdk server-only

Đặt khóa vào .env.local. Khóa không có tiền tố NEXT_PUBLIC_, nên chỉ nằm trên máy chủ:

K_OTP_SECRET_KEY=sk_test_...

Luồng hoạt động như thế nào

  1. sendCode(phoneNumber) gọi issue với một mục đích ("login") và một khóa idempotency. K-OTP tạo mã và gửi qua KakaoTalk AlimTalk.
  2. Máy chủ của bạn lưu phiên đăng nhập đang chờ: số điện thoại, khóa idempotency và issueId mà issue trả về.
  3. verifyCode(code) gọi verify với issueId đó. Mã sai là một kết quả bình thường (verified: false kèm reasonCode), không phải exception. Theo mặc định, mã có hiệu lực trong 3 phút và cho phép 5 lần thử.

1. Client máy chủ

// lib/otp.ts
import "server-only";

import { createOtpServerClient } from "@k-otp/sdk/server";

// The key is read when a request is made, so a missing variable fails that request, not the build.
export const otp = createOtpServerClient({
	apiKey: () => process.env.K_OTP_SECRET_KEY ?? "",
});

createOtpServerClient chỉ chấp nhận khóa sk_. Chỉ import nó từ mã phía máy chủ: server-only sẽ làm build thất bại nếu một client component import file này.

2. Phiên đăng nhập đang chờ được lưu ở đâu

Kết quả verify chỉ có giá trị khi nó gắn với số điện thoại mà mã đã được gửi tới. Hãy giữ liên kết đó trên máy chủ, không phải trong cookie mà trình duyệt có thể sửa. Ví dụ này dùng một map trong bộ nhớ với khóa là session id; hãy thay bằng session store hoặc cơ sở dữ liệu của bạn (Map sẽ mất khi khởi động lại và không được chia sẻ giữa các instance).

// lib/pending-otp.ts
import "server-only";

export type PendingOtp = {
	phoneNumber: string;
	/** Saved before calling issue and reused when the same send is retried. */
	idempotencyKey: string;
	/** Set once issue succeeded. */
	issueId?: string;
	/** When the last code was sent (epoch ms), for the resend cooldown. */
	sentAt?: number;
};

// Example only: one process, lost on restart. Use your session store or database instead.
const store = new Map<string, PendingOtp>();

export const pendingOtp = {
	get: async (sessionId: string) => store.get(sessionId),
	set: async (sessionId: string, value: PendingOtp) => {
		store.set(sessionId, value);
	},
	delete: async (sessionId: string) => {
		store.delete(sessionId);
	},
};

3. Server Actions: gửi và xác minh

// app/login/actions.ts
"use server";

import { randomUUID } from "node:crypto";

import { isAmbiguousIssueError } from "@k-otp/sdk";
import { createIdempotencyKey, getIssueRequestErrorCode, isOtpApiError } from "@k-otp/sdk/server";
import { parseOtpPhoneNumber } from "@k-otp/sdk/ui";
import { cookies } from "next/headers";

import { otp } from "@/lib/otp";
import { type PendingOtp, pendingOtp } from "@/lib/pending-otp";
import { signIn } from "@/lib/session"; // your own session code

const RESEND_COOLDOWN_MS = 30_000;

export type SendCodeResult =
	| { ok: true; expiresAt: string; resendInMs: number }
	| {
			ok: false;
			error: "INVALID_PHONE" | "COOLDOWN" | "RATE_LIMITED" | "RETRY" | "UNAVAILABLE";
			retryInMs?: number;
	  };

export type VerifyCodeResult =
	| { ok: true }
	| {
			ok: false;
			error: "NO_CODE" | "MISMATCH" | "NEW_CODE_NEEDED" | "RATE_LIMITED" | "RETRY";
			attemptsRemaining?: number;
			retryInMs?: number;
	  };

async function getSessionId() {
	const jar = await cookies();
	const existing = jar.get("otp_sid")?.value;
	if (existing) return existing;
	const sessionId = randomUUID();
	jar.set("otp_sid", sessionId, {
		httpOnly: true,
		secure: process.env.NODE_ENV === "production",
		sameSite: "lax",
		path: "/",
	});
	return sessionId;
}

export async function sendCode(input: string): Promise<SendCodeResult> {
	// Korean mobile numbers only: "010-1234-5678" -> "01012345678", anything else -> undefined.
	const phoneNumber = parseOtpPhoneNumber(input).value;
	if (!phoneNumber) return { ok: false, error: "INVALID_PHONE" };
	// Add your own abuse checks here (CAPTCHA, limits per user or IP).

	const sessionId = await getSessionId();
	const previous = await pendingOtp.get(sessionId);

	if (previous?.sentAt && previous.phoneNumber === phoneNumber) {
		const waitMs = previous.sentAt + RESEND_COOLDOWN_MS - Date.now();
		if (waitMs > 0) return { ok: false, error: "COOLDOWN", retryInMs: waitMs };
	}

	// Retrying a send that never got an answer (same number, no issueId yet): reuse its key.
	// Anything else is a new attempt with a new key.
	const pending: PendingOtp =
		previous && !previous.issueId && previous.phoneNumber === phoneNumber
			? previous
			: { phoneNumber, idempotencyKey: createIdempotencyKey("login") };
	await pendingOtp.set(sessionId, pending); // save the key BEFORE calling issue

	try {
		const result = await otp.issue({
			phoneNumber: pending.phoneNumber,
			purpose: "login",
			idempotencyKey: pending.idempotencyKey,
		});
		await pendingOtp.set(sessionId, { ...pending, issueId: result.issueId, sentAt: Date.now() });
		return { ok: true, expiresAt: result.expiresAt, resendInMs: RESEND_COOLDOWN_MS };
	} catch (error) {
		if (!isOtpApiError(error)) throw error;

		if (isAmbiguousIssueError(error)) {
			// The code may already be on its way. Keep the key: a retry is replayed, not sent again.
			if (error.code === "TOO_MANY_REQUESTS") {
				return { ok: false, error: "RATE_LIMITED", retryInMs: error.retryAfterMs ?? 30_000 };
			}
			return { ok: false, error: "RETRY" };
		}

		// A definite rejection: nothing was sent, and the next send gets a new key.
		await pendingOtp.delete(sessionId);
		const requestError = getIssueRequestErrorCode(error); // e.g. TEMPLATE_NOT_AVAILABLE
		if (!requestError && error.code === "BAD_REQUEST") return { ok: false, error: "INVALID_PHONE" };
		// PAYMENT_REQUIRED (out of credit), UNAUTHORIZED, FORBIDDEN, ...: your problem, not the user's.
		console.error("K-OTP issue failed", requestError ?? error.code, error.requestId);
		return { ok: false, error: "UNAVAILABLE" };
	}
}

export async function verifyCode(code: string): Promise<VerifyCodeResult> {
	const sessionId = await getSessionId();
	const pending = await pendingOtp.get(sessionId);
	if (!pending?.issueId) return { ok: false, error: "NO_CODE" };
	if (!/^\d{6}$/.test(code)) return { ok: false, error: "MISMATCH" };

	try {
		const result = await otp.verify({ issueId: pending.issueId, code });
		// ALREADY_VERIFIED: an earlier verify of this session succeeded but its answer was lost.
		if (result.verified || result.reasonCode === "ALREADY_VERIFIED") {
			await pendingOtp.delete(sessionId);
			await signIn(pending.phoneNumber);
			return { ok: true };
		}
		if (result.reasonCode === "MISMATCH") {
			return { ok: false, error: "MISMATCH", attemptsRemaining: result.attemptsRemaining };
		}
		return { ok: false, error: "NEW_CODE_NEEDED" }; // EXPIRED, MAX_ATTEMPTS, REPLACED, NOT_FOUND
	} catch (error) {
		if (!isOtpApiError(error)) throw error;
		if (error.code === "TOO_MANY_REQUESTS") {
			return { ok: false, error: "RATE_LIMITED", retryInMs: error.retryAfterMs ?? 30_000 };
		}
		console.error("K-OTP verify failed", error.code, error.requestId);
		return { ok: false, error: "RETRY" }; // verify is safe to retry
	}
}

signIn đại diện cho mã quản lý phiên của riêng bạn: hãy tạo phiên cho số điện thoại đã xác minh ở đó.

Khóa idempotency, từng bước một

issue gửi một tin nhắn thật và tốn một credit, nên SDK yêu cầu khóa idempotency ở mọi lần gọi. Các quy tắc trong sendCode:

  • Một khóa cho mỗi lần thử gửi. createIdempotencyKey("login") tạo khóa, và khóa được lưu trước khi gọi issue.
  • Kết quả không rõ, cùng khóa. Sau timeout, lỗi mạng, 503 hoặc 429, mã có thể đã đang trên đường đi. isAmbiguousIssueError(error) trả về true cho đúng những trường hợp này. Bản ghi đang chờ giữ nguyên khóa, nên khi người dùng bấm nút lần nữa, K-OTP trả lại kết quả đầu tiên thay vì gửi tin nhắn thứ hai hoặc tính phí hai lần.
  • Kết quả rõ ràng, khóa mới. Sau khi thành công hoặc bị từ chối (400, 401, 402, 403, 409), lần gửi tiếp theo là một lần thử mới. Số điện thoại bị thay đổi cũng là một lần thử mới: dùng lại khóa với payload khác sẽ bị từ chối với 409 CONFLICT.

Lưu ý các import: isAmbiguousIssueError đến từ @k-otp/sdk; client máy chủ và các helper khác đến từ @k-otp/sdk/server.

Những lỗi người dùng có thể tự xử lý

  • TOO_MANY_REQUESTS (429): đã áp dụng giới hạn tần suất. error.retryAfterMs cho biết cần chờ bao lâu; form chuyển giá trị này thành bộ đếm ngược.
  • BAD_REQUEST (400): thường là do số điện thoại. getIssueRequestErrorCode(error) tách riêng các mã ở cấp request (CHANNEL_NOT_SUPPORTED, TEMPLATE_NOT_AVAILABLE, WEB_OTP_NOT_SUPPORTED), vốn là lỗi trong request của bạn chứ không phải dữ liệu người dùng nhập.
  • PAYMENT_REQUIRED (402): tổ chức của bạn đã hết credit. Đó không phải lỗi của người dùng: hãy hiển thị một thông báo chung và tự gửi cảnh báo cho mình.

Thời gian chờ gửi lại được áp dụng trên máy chủ (ở đây là 30 giây), nên vẫn có hiệu lực ngay cả khi ai đó gọi action trực tiếp. Server Actions là endpoint công khai: hãy thêm các biện pháp chống lạm dụng của riêng bạn tại chỗ có comment hướng dẫn.

4. Form

Form gọi hai action và dùng OtpCodeInput từ @k-otp/sdk/ui/react, một ô nhập mã headless chia ô, hỗ trợ dán, điều hướng bằng bàn phím và autocomplete="one-time-code". Nó không cần khóa: nó chỉ chỉnh sửa một giá trị.

// app/login/login-form.tsx
"use client";

import { OtpCodeInput } from "@k-otp/sdk/ui/react";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";

import { type SendCodeResult, type VerifyCodeResult, sendCode, verifyCode } from "./actions";

type SendError = Extract<SendCodeResult, { ok: false }>["error"];
type VerifyError = Extract<VerifyCodeResult, { ok: false }>["error"];

const SEND_ERRORS: Record<SendError, string> = {
	INVALID_PHONE: "Check the mobile number.",
	COOLDOWN: "Please wait before requesting another code.",
	RATE_LIMITED: "Too many requests. Please wait a moment.",
	RETRY: "We could not confirm the code was sent. Try again.",
	UNAVAILABLE: "Sending codes is unavailable right now. Please try later.",
};

const VERIFY_ERRORS: Record<VerifyError, string> = {
	NO_CODE: "Request a code first.",
	MISMATCH: "Wrong code.",
	NEW_CODE_NEEDED: "This code can no longer be used. Request a new one.",
	RATE_LIMITED: "Too many attempts. Please wait a moment.",
	RETRY: "Something went wrong. Try again.",
};

export function LoginForm() {
	const router = useRouter();
	const [phoneNumber, setPhoneNumber] = useState("");
	const [code, setCode] = useState("");
	const [codeSent, setCodeSent] = useState(false);
	const [message, setMessage] = useState("");
	const [waitUntil, setWaitUntil] = useState(0);
	const [now, setNow] = useState(() => Date.now());
	const [isPending, startTransition] = useTransition();

	// Tick once a second while a cooldown runs.
	useEffect(() => {
		if (waitUntil <= now) return;
		const timer = setTimeout(() => setNow(Date.now()), 1000);
		return () => clearTimeout(timer);
	}, [waitUntil, now]);
	const waitSeconds = Math.max(0, Math.ceil((waitUntil - now) / 1000));

	const send = () =>
		startTransition(async () => {
			const result = await sendCode(phoneNumber);
			setNow(Date.now());
			if (result.ok) {
				setCodeSent(true);
				setCode("");
				setWaitUntil(Date.now() + result.resendInMs);
				setMessage("We sent a code by KakaoTalk.");
				return;
			}
			if (result.retryInMs) setWaitUntil(Date.now() + result.retryInMs);
			setMessage(SEND_ERRORS[result.error]);
		});

	const verify = (value: string) =>
		startTransition(async () => {
			const result = await verifyCode(value);
			if (result.ok) {
				router.push("/");
				return;
			}
			setCode("");
			if (result.retryInMs) {
				setNow(Date.now());
				setWaitUntil(Date.now() + result.retryInMs);
			}
			const left = result.attemptsRemaining;
			setMessage(`${VERIFY_ERRORS[result.error]}${left ? ` ${left} attempts left.` : ""}`);
		});

	return (
		<form onSubmit={(event) => event.preventDefault()}>
			<label htmlFor="phone">Mobile number</label>
			<input
				id="phone"
				type="tel"
				autoComplete="tel"
				value={phoneNumber}
				onChange={(event) => setPhoneNumber(event.target.value)}
			/>
			<button type="button" onClick={send} disabled={isPending || waitSeconds > 0}>
				{waitSeconds > 0 ? `Resend in ${waitSeconds}s` : codeSent ? "Resend code" : "Send code"}
			</button>

			{codeSent && (
				<OtpCodeInput
					aria-label="Verification code"
					locale="en"
					value={code}
					onValueChange={setCode}
					onComplete={verify}
					readOnly={isPending}
					autoFocus
				/>
			)}

			<p role="status">{message}</p>
		</form>
	);
}
// app/login/page.tsx
import { LoginForm } from "./login-form";

export default function LoginPage() {
	return (
		<main>
			<h1>Log in</h1>
			<LoginForm />
		</main>
	);
}

Component này không có style. Để dùng giao diện mặc định, hãy import @k-otp/sdk/ui/theme.css, hoặc tự tạo style cho các thuộc tính data-k-otp; xem Component UI.

Dùng thử ở chế độ thử nghiệm

Với khóa sk_test_, K-OTP không gửi gì và không tốn credit. Nó chỉ chấp nhận các số thử nghiệm, trong đó hai chữ số cuối chọn một kịch bản, và mọi mã thử nghiệm đều là 000000.

  • 010-0000-0000: mã được tính là đã gửi tới, và 000000 sẽ đăng nhập cho bạn.
  • 010-0000-0005: mọi mã đều sai, nên bạn thấy số lần thử giảm dần.
  • 010-0000-0006: lỗi 429, nên nút hiển thị bộ đếm ngược 60 giây.
  • 010-0000-0007: lỗi 402, nên người dùng thấy thông báo chung "Sending codes is unavailable right now. Please try later." và log máy chủ của bạn hiển thị lỗi.
  • 010-0000-0009: lỗi 503, nên người dùng thấy "We could not confirm the code was sent. Try again." Bấm gửi lần nữa sẽ thử lại với cùng khóa thay vì bắt đầu một lần gửi mới.

Số thật dùng với khóa thử nghiệm sẽ bị từ chối với 400 (TEST_NUMBER_REQUIRED), và form hiển thị là "Check the mobile number." Test inbox trên console liệt kê các lần phát hành thử nghiệm của bạn. Mọi kịch bản đều có trong hướng dẫn chế độ thử nghiệm.

Trước khi đưa vào vận hành

  • Thay sk_test_ bằng khóa sk_ live trong môi trường production. Khóa live từ chối các số thử nghiệm.
  • Gửi vài mã thật tới điện thoại của đội bạn. Mỗi lần gửi live tốn 1 credit; các lệnh gọi verify miễn phí.
  • Chuyển trạng thái đang chờ sang session store hoặc cơ sở dữ liệu của bạn.
  • Giữ các biện pháp chống lạm dụng của riêng bạn ở phía trước sendCode.

Muốn dùng form dựng sẵn?

OtpForm từ @k-otp/sdk/ui/react hiển thị toàn bộ luồng (ô số điện thoại, gửi và gửi lại, ô nhập mã, bộ đếm ngược, thông báo) và gọi K-OTP trực tiếp từ trình duyệt với khóa công khai pk_. Cách này thiết lập nhanh hơn, nhưng việc xác minh phía trình duyệt chỉ cho trình duyệt biết rằng mã đã khớp. Nếu máy chủ của bạn cấp quyền truy cập dựa trên kết quả đó, hãy xác nhận trên máy chủ bằng getStatus({ issueId }) và khóa sk_. Luồng do máy chủ điều khiển ở trên tránh được bước đó.

Đọc tiếp