typescript 11 lines · 1 tab

OAuth PKCE flow (high level helper)

Mateo Rodriguez Jan 2026
1 tab
import crypto from 'node:crypto';

export function base64url(buf: Buffer) {
  return buf.toString('base64').replace(/+/g, '-').replace(///g, '_').replace(/=+$/g, '');
}

export function createPkcePair() {
  const verifier = base64url(crypto.randomBytes(32));
  const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());
  return { verifier, challenge, method: 'S256' as const };
}
1 file · typescript Explain with highlit

OAuth flows are a minefield, and PKCE is the safe default for public clients. I generate a verifier, derive a challenge, store the verifier in a short-lived session, and then exchange the authorization code for tokens. The key detail is treating the verifier like a secret: keep it server-side when possible, or store it in a secure, short-lived cookie if you’re doing a pure browser flow. I also validate state to prevent CSRF. In production I prefer a well-maintained OAuth library, but understanding the moving parts helps debug ‘works locally but not in prod’ issues around redirect_uri, scopes, and token lifetimes.


Related snips

Share this code

Here's the card — post it anywhere.

OAuth PKCE flow (high level helper) — share card
Link copied