# Use 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:

```ts
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`.

---

Want to master secure OAuth2 flows in React Router apps?

📘 My book *React Router OAuth2 Handbook* is now available!

It covers everything from the basics to advanced topics like PKCE, refresh tokens, and E2E auth testing.

→ [books.sergiodxa.com/release](https://go.sergiodxa.com/x6EE88z)
