🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

MFA, Refresh Tokens, and OAuth PKCE in Next.js

Next.js SecurityđŸŸĸ Free Lesson

MFA, Refresh Tokens, and OAuth PKCE in Next.js

Password login answers one question — does this person know a secret — and every serious security incident that starts with a stolen password shows why that single question is not enough. The second factor, the token lifetime, and the sign-in redirect each solve a different problem, and conflating them produces applications that are simultaneously annoying and insecure: long-lived tokens with a mandatory SMS code, or short tokens that silently log users out every quarter hour.

This lesson works through the three pieces separately. A second factor that verifies possession of a device, a token pair whose rotation limits what a stolen credential can do, and an OAuth flow that never lets the secret touch a browser it does not control.

Prerequisites

  • !Session handling and cookies in Next.js
  • !Route handlers and middleware
  • !Comfort with async JavaScript and JSON Web Tokens

What You'll Learn

  • 1Choose an access and refresh token split with concrete lifetimes
  • 2Verify a TOTP code with tolerance for clock drift
  • 3Complete the OAuth authorization code flow with PKCE
  • 4Link a second provider to an existing account without creating a duplicate

What changes once a password is not enough

Two factors means two independent proofs: something you know, and something you have. In practice the second factor is a time-based one-time password from an authenticator app, a passkey, or a hardware key. The design consequence is that verification becomes a two-step protocol rather than a single form: first prove the password, then prove the device, and only then issue credentials.

That ordering matters for more than UX. If you issue a session after the password check and upgrade it later, an attacker who has stolen the password has a usable window while the user is distracted by the code prompt. The correct shape is a short-lived pending state — a record saying "this password was valid, this login is not finished" — that only becomes a real session when the second proof arrives.

// app/api/auth/mfa/verify/route.js
import { NextResponse } from 'next/server';
import { verifyTotp } from '@/lib/totp';
import { createSession } from '@/lib/session';
import { pendingLogins, consumePending } from '@/lib/pending-login';

export async function POST(request) {
  const { requestId, code } = await request.json();
  const pending = consumePending(requestId);

  // The pending record expires quickly: a half-finished login is a liability.
  if (!pending) {
    return NextResponse.json({ error: 'Sign-in expired, start again' }, { status: 410 });
  }

  // Drift tolerance of one step either way covers a slow phone clock.
  const ok = verifyTotp(pending.secret, code, { window: 1 });
  if (!ok) {
    return NextResponse.json({ error: 'Incorrect code' }, { status: 401 });
  }

  await createSession(pending.userId);
  return NextResponse.json({ ok: true });
}

Two failure modes are visible in that handler. A code attempt that does not match must not reveal whether the request id or the code was wrong — a single generic message keeps the guessing game closed. And the pending record should be consumed on use, so the same code cannot be replayed even inside its thirty-second window.

Access and refresh tokens with rotation

The split is a trade between risk and re-authentication. An access token that lives for fifteen minutes limits how much a stolen token can do; a refresh token that lives for days removes the need to type a password every fifteen minutes. Rotation closes the remaining hole: when a refresh token is used, issue a new one and invalidate the old, so a token captured from a network trace or a log file is already dead by the time anyone replays it.

// lib/tokens.js
import { SignJWT, jwtVerify } from 'jose';

const secret = new TextEncoder().encode(process.env.AUTH_SECRET);

export async function issueTokens(user) {
  const accessToken = await new SignJWT({ sub: user.id, role: user.role })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('15m')
    .sign(secret);

  const refreshToken = await new SignJWT({ sub: user.id, jti: crypto.randomUUID() })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('7d')
    .sign(secret);

  return { accessToken, refreshToken };
}

export async function rotateRefreshToken(token) {
  const { payload } = await jwtVerify(token, secret);

  // Replay detection: this id was already spent.
  if (await tokenStore.wasUsed(payload.jti)) {
    await tokenStore.revokeAll(payload.sub);
    throw new Error('Refresh token reuse detected');
  }

  await tokenStore.markUsed(payload.jti, Date.now());
  const user = await getUser(payload.sub);
  return issueTokens(user);
}

Reuse detection is the part most implementations leave out, and it is the part that catches real theft. If a refresh token is presented twice, exactly one of two things is true: either the attacker has the copy or the legitimate client does. Revoking the whole family for that user and forcing a fresh sign-in is the only response that is correct in both cases.

Store the refresh token server-side — in a database or a signed, httpOnly, SameSite=Strict cookie — and keep the access token short enough that it can live anywhere. Long-lived bearer tokens in localStorage turn every cross-site scripting bug into a full account takeover, which is a bet you do not want to make.

The OAuth flow with PKCE

For "sign in with Google", the authorization code flow sends the user to the provider and brings them back with a short code that the server exchanges for tokens. On a server-rendered Next.js app the client secret can stay on the server, which is the whole reason to prefer the code flow over the implicit flow. PKCE adds one extra trick for clients that cannot keep a secret: generate a random string, send only its hash with the request, and prove knowledge of the original when redeeming the code.

// app/api/auth/oauth/callback/route.js
import { NextResponse } from 'next/server';

const verifier = () =>
  btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

export async function GET(request) {
  const url = new URL(request.url);
  const code = url.searchParams.get('code');
  const state = url.searchParams.get('state');
  const stored = await takeState(state);

  // state must match what we sent, otherwise this is a CSRF login attempt.
  if (!stored || stored.expiresAt < Date.now()) {
    return NextResponse.redirect(new URL('/login?error=state', request.url));
  }

  const tokens = await exchangeCode({
    code,
    codeVerifier: stored.verifier,
    redirectUri: `${process.env.APP_URL}/api/auth/oauth/callback`,
  });

  const profile = await fetchProfile(tokens.accessToken);
  const user = await findOrCreateUser(profile);

  await createSession(user.id);
  return NextResponse.redirect(new URL('/dashboard', request.url));
}

The state check is not decorative. Without it, an attacker can start a flow, capture their own callback link, and trick a signed-in victim into clicking it, binding the victim's session to the attacker's account. Comparing state to a server-stored value makes that forgery fail.

Picking a second factor people will finish

Every second factor trades security against friction, and the friction is not theoretical: a factor users hate is a factor they will try to route around. SMS codes are better than nothing and worse than everything else here, because a phone number can be socially engineered and a SIM can be swapped. TOTP from an authenticator app removes the network dependency and works offline, at the cost of a setup step that loses people who never scanned the QR code properly. Passkeys remove the shared secret entirely — there is nothing to phish and nothing to type — but they introduce device and platform questions that support teams must be ready to answer.

Whichever you choose, recovery codes are not optional. A user locked out of their only factor is a support ticket that ends with an identity check, and issuing ten single-use codes at enrolment converts most of those into a self-service flow. Store them hashed, show them exactly once, and let a user regenerate them after they have been used. Also keep an eye on the failure counter: unlimited code attempts turn a six-digit space into a brute-force problem, so lock the account briefly after a handful of consecutive failures rather than trusting the size of the code alone.

Sessions that end when the user says so

Issuing a session is easy; revoking one is where implementations get sloppy. The test that separates the two is simple: if the user clicks sign out on their phone, does the session they opened on their laptop still work? With a stateless token and no server-side record, the answer is yes until the token expires, and there is no way to force it otherwise.

// lib/session.js — a session record you can actually revoke
export async function createSession(userId, { userAgent }) {
  const id = crypto.randomUUID();
  await sessionStore.create({
    id,
    userId,
    userAgent,
    createdAt: Date.now(),
    expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
    revokedAt: null,
  });
  return id;
}

export async function verifySession(id) {
  const record = id ? await sessionStore.find(id) : null;
  if (!record || record.revokedAt || record.expiresAt < Date.now()) {
    throw new Error('Invalid session');
  }
  return record;
}

export async function revokeSession(id) {
  await sessionStore.update(id, { revokedAt: Date.now() });
}

export async function revokeAllForUser(userId) {
  // Called on password change, suspected compromise, or MFA enrolment.
  await sessionStore.revokeAll({ userId });
}

Keep the cookie itself boring — an opaque id, httpOnly, Secure, SameSite set deliberately — and put the authority on the server. Then signing out, changing a password, or detecting a leaked token becomes a single row update rather than an attempt to recall a token that is already in someone else's storage. List active sessions with their user agent and last-seen time in the account settings, because "where am I signed in" is the first question a user asks after a scare.

Linking providers to one identity

A user who signs in with Google on Monday and GitHub on Friday should not end up with two accounts. Linking is therefore an identity operation rather than a settings page: record (provider, providerUserId) against one existing user id, and make that pair unique so a second login cannot silently create a second row.

The dangerous path is auto-linking on matching email addresses, because an unverified email at one provider is attacker-controllable input. Link only from an authenticated session — a user who is already signed in and explicitly clicks "connect GitHub" — and never let an incoming login create a link by itself. The table below summarises where each decision belongs.

DecisionRecommended valueWhy
Access token lifetime10 to 15 minutesBounds damage from a leaked bearer token
Refresh token lifetime7 to 30 days with rotationAvoids daily password prompts
TOTP windowÂą1 step (30 seconds)Tolerates phone clock drift
Pending login TTL5 minutesHalf-finished logins expire quickly
Email-based auto-linkNeverProvider emails can be unverified
Session cookiehttpOnly, Secure, SameSiteBlocks script access and cross-site sends

Common Mistakes

Issuing a session right after the password check, before the second factor

Fix: Hold a short-lived pending state and only create the session once the TOTP code verifies.

Accepting a refresh token forever without invalidating it

Fix: Rotate on every use and revoke the entire token family when a jti is presented twice.

Storing bearer tokens in localStorage

Fix: Prefer httpOnly cookies for anything long-lived; localStorage is readable by any injected script.

Auto-linking accounts when provider emails match

Fix: Link only from an authenticated session where the user explicitly connects the provider.

Best Practices

  • Keep the second factor verification in its own route handler with generic failure messages
  • Log every rotation and reuse event with the user id, since those are your intrusion signals
  • Validate OAuth state before exchanging the code, and use PKCE on every client type
  • Offer passkeys as the second factor where the platform supports them

Interview Questions

Q1: Why rotate refresh tokens instead of using one long-lived token?

Rotation bounds the useful life of a stolen token and lets you detect replay: a token family that is used twice proves one copy was stolen, so you revoke the family.

Q2: What does PKCE protect against?

It prevents an authorization code from being redeemed by anyone who did not initiate the flow, because the redeemer must present the original random verifier whose hash was sent with the request.

Q3: Why must state be checked on the OAuth callback?

It ties the callback to the browser that started the request, blocking the login CSRF attack where a victim is tricked into completing an attacker-initiated sign-in.

Key Takeaways

  • Second-factor verification happens before any session exists, through a short-lived pending record.
  • Short access tokens plus rotating refresh tokens with reuse detection limit what a stolen credential can do.
  • PKCE and a validated state parameter cover the two classic OAuth weaknesses: code interception and login CSRF.
  • Account linking must be an explicit action from an authenticated session, never an automatic email match.
  • Every lifetime in the system is a decision worth writing down; defaults of 15 minutes and 7 days are a sound starting point.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement