How-To Guide

How to Implement OAuth 2.0 PKCE for SPAs

Add Proof Key for Code Exchange to a single-page app so a public client can use the authorization code flow without shipping a client secret.

On this page

  1. Introduction
  2. Why Public Clients Need PKCE
  3. Generating the Code Verifier and Challenge
  4. Sending the Authorization Request
  5. Exchanging the Code for Tokens
  6. Validating State, Nonce and Redirect URI
  7. Refresh Tokens in Public Clients
  8. Conclusion

Introduction

OAuth 2.0 originally assumed the client could keep a secret, which made native apps and single-page applications awkward: any secret embedded in shipped JavaScript or an installed binary is readable by the user. The authorization code flow with Proof Key for Code Exchange (PKCE, pronounced “pixy”) fixes that by replacing the static client secret with a one-time secret generated for each authorization attempt. The authorization server stores a hash of that secret when the flow starts and verifies it when the code is redeemed, so an attacker who intercepts the authorization code still cannot exchange it for tokens. This article walks through the complete PKCE handshake as it applies to a browser-based public client.

Why Public Clients Need PKCE

A public client is any client that cannot keep a credential secret: a browser SPA, a desktop app, a mobile app, or a CLI. In the original authorization code flow the client authenticated with a client_secret at the token endpoint. For a public client that secret lives in shipped code, so it is not a secret at all. Some deployments used the implicit flow instead, which returns the access token directly in the redirect fragment; that avoids the secret but exposes the token to the URL, browser history, and any script on the redirect page. PKCE keeps the safer code flow and adds a per-request proof that the client redeeming the code is the same client that started the flow.

The specific threat PKCE defeats is authorization code interception. On mobile, a malicious app can register the same custom URL scheme and receive the redirect. On the web, an attacker with a foothold in the browser could read the code. Without PKCE an intercepted code is immediately redeemable; with PKCE it is useless without the code_verifier, which never leaves the client that created it. OAuth 2.1 makes PKCE mandatory for every client that uses the authorization code flow, not only public ones.

Generating the Code Verifier and Challenge

The client picks a high-entropy code_verifier, a random string of 43 to 128 characters from the unreserved set, and derives the code_challenge as BASE64URL(SHA-256(verifier)). Only the challenge travels in the authorization request; the verifier stays in client storage until the token exchange. Generating 32 random bytes and base64url-encoding them yields exactly 43 characters, which sits inside the allowed range without padding.

function base64UrlEncode(bytes) {
  let str = btoa(String.fromCharCode(...bytes));
  return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

async function createPkcePair() {
  const random = crypto.getRandomValues(new Uint8Array(32));
  const verifier = base64UrlEncode(random);            // 43 chars, within 43-128
  const digest = await crypto.subtle.digest(
    'SHA-256',
    new TextEncoder().encode(verifier),
  );
  return { verifier, challenge: base64UrlEncode(new Uint8Array(digest)) };
}

Sending the Authorization Request

The authorization request is a browser redirect to the authorization endpoint carrying response_type=code, client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256. The state value is an unguessable random string the client stores locally and checks when the redirect returns; it binds the response to the request and blocks cross-site request forgery against the redirect handler. Never derive state from a counter, a timestamp or anything predictable.

Use code_challenge_method=S256, not plain. The plain method sends the verifier essentially unhashed and exists only as a compatibility fallback. Every current authorization server supports S256; if a provider only supports plain, that is a strong signal to choose a different provider. Also request only the scopes you actually use, because scopes translate into what a stolen token can do.

Exchanging the Code for Tokens

When the provider redirects back to the registered redirect_uri with a code and the original state, the client verifies state and then posts the code together with the code_verifier to the token endpoint. The provider recomputes the challenge from the verifier and rejects the exchange if it does not match the challenge it stored at authorization time. The redirect_uri in the exchange must also match the one used in the request, byte for byte.

async function exchangeCode(params) {
  const { code, verifier, state, expectedState, redirectUri, tokenEndpoint, clientId } = params;
  if (state !== expectedState) throw new Error('state mismatch: possible CSRF');
  const body = new URLSearchParams({
    grant_type: 'authorization_code',
    code,
    code_verifier: verifier,
    redirect_uri: redirectUri,
    client_id: clientId,
  });
  const res = await fetch(tokenEndpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body,
  });
  if (!res.ok) throw new Error('token exchange failed: ' + res.status);
  return res.json(); // { access_token, refresh_token?, id_token?, expires_in }
}

Validating State, Nonce and Redirect URI

State defeats CSRF and nonce defeats ID token replay. If the client requests an OpenID Connect id_token, it sends a nonce in the authorization request and verifies that the nonce claim in the returned id_token matches the value it sent. The redirect_uri must match the one registered with the provider exactly; an authorization server that allows wildcard or prefix matching lets an attacker redirect the code to a host they control, which is the classic open redirect that PKCE alone does not stop.

Treat the access token and refresh token as sensitive. Store them in memory where possible; when you must persist them across reloads, prefer a server-side session with an HttpOnly, Secure, SameSite cookie over localStorage, because any XSS on the page can read localStorage. This mirrors secure session handling in server-rendered apps: the credential should be unreadable by page scripts.

Refresh Tokens in Public Clients

Refresh tokens let a SPA obtain new access tokens without another redirect, but in a public client the refresh token is long-lived and powerful. Providers mitigate this with refresh token rotation: each refresh returns a new refresh token and invalidates the previous one. If a rotated-away token is presented again, the provider assumes theft and revokes the entire token family, so a stolen token becomes detectable rather than silently usable forever.

Send the client_id with refresh requests only when the provider requires it for public clients, and never attach a client_secret. Limit the refresh token to the scopes the app needs and call the provider’s revocation endpoint on logout so the token cannot be replayed. For your own APIs, verify the access token’s audience and issuer, because a token minted for a different client or a different environment is not valid for your service just because its signature checks out.

Conclusion

PKCE turns the authorization code flow into something safe for public clients by replacing a shared secret with a per-request proof. Generate a fresh verifier and S256 challenge for every attempt, carry state and nonce through the redirect, verify both on return, exchange the code with the verifier, and store tokens where XSS cannot reach them. Verify the resulting token’s signature, issuer, audience and expiry before trusting it. Do all of that and you get the security of a confidential client’s code flow without shipping a secret you cannot keep.

Sources: RFC 7636: PKCE, OAuth 2.0 Security Best Current Practice, OAuth 2.0 Authorization Framework (RFC 6749).

FAQ

Is PKCE enough on its own to secure a browser app?
No. PKCE protects the token exchange from code interception, but you still need exact redirect_uri matching, state for CSRF, nonce for ID token replay, and safe token storage. PKCE complements those controls rather than replacing them.
Must the code_verifier be regenerated for every authorization attempt?
Yes. Reusing a verifier across attempts weakens the guarantee that the client redeeming the code started that specific flow. Generate a fresh verifier and challenge per request and discard the state after the exchange.

Related Examples