How toUse PKCE in OAuth2 Authorization Code Flow

PKCE (Proof Key for Code Exchange) is a security extension to the OAuth2 Authorization Code flow. It protects against code interception attacks by requiring a client-generated secret (the verifier) when exchanging the authorization code for tokens.

PKCE is essential for public clients that can’t safely store secrets—like mobile apps and SPAs.

It’s also recommended for server-rendered web apps as an extra layer of protection against authorization code interception.

Generating the code verifier and challenge

To use PKCE, the client generates a code_verifier and a derived code_challenge. Here's how to do it securely:

let code_verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));

let buffer = new TextEncoder().encode(code_verifier);
let digest = await crypto.subtle.digest("SHA-256", buffer);

let code_challenge = base64url(new Uint8Array(digest));
  • code_challenge is sent when initiating the OAuth2 flow.
  • code_verifier is kept secret and used later when redeeming the authorization code.

Even if an attacker intercepts the code, they can’t exchange it without the original code_verifier.


I'm writing a book about OAuth2 in modern web apps using React Router & Remix.

The landing page is live—book coming soon: books.sergiodxa.com