Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Beyond Fetch

OAuth, Tokens and Sessions for API Calls

Authenticate API calls from the browser - sessions versus bearer tokens, access and refresh tokens, a safe refresh wrapper for fetch, token storage trade-offs and the OAuth PKCE flow.

Almost every real API has to answer one question before it does anything: who is asking? A public weather feed may not care, but the moment a request reads someone's orders, posts a comment or charges a card, the server needs proof of identity. In the browser, that proof usually travels in one of two shapes: a session cookie the browser attaches automatically, or a token your JavaScript puts in an Authorization header.

Headers, Auth and CORS Basics showed the Authorization: Bearer header itself. This lesson covers everything around it: how sessions and tokens differ, why tokens expire and how to refresh them without breaking the page, where tokens may be stored, and what OAuth 2.0 with PKCE is doing when you click "Sign in with Google". Most of the code runs here against a stand-in server, because the sandbox cannot talk to a real identity provider.

Sessions versus tokens

There are two common designs, and many apps use both:

Session cookie Bearer token
What the browser holds An opaque ID in a cookie A token string in memory or storage
Who attaches it The browser, automatically, on every request to that site Your JavaScript, in an Authorization header
Server state Server looks the ID up in a session store Often none: the token itself carries and proves the claims (for example a JWT)
Revoking Delete the session on the server: instant Hard until the token expires, unless the server keeps a deny list
Main risk CSRF: another site can make the browser send the cookie XSS: injected script can read the token
Best for A website and API on the same site APIs used by several apps or domains, mobile apps, third-party access

A cookie-based call needs one setting to be sent to a different origin: fetch(url, { credentials: "include" }), plus matching CORS headers and SameSite rules on the server. A cookie marked HttpOnly cannot be read by JavaScript at all, which is a strong defense against token theft; see Cookies and Security for AJAX for the protective flags (Secure, HttpOnly, SameSite).

What is inside a token?

An opaque token is a random string that means nothing by itself; the server looks it up. A JWT (JSON Web Token) is different: three Base64URL parts separated by dots (header.payload.signature) where the payload holds readable claims such as who the user is (sub) and when the token stops being valid (exp, in seconds since 1970). The signature lets the server detect tampering.

Your front-end code may read a JWT payload, for example to know when to refresh, but must never trust it for security decisions: anyone can edit the payload text, and only the server can verify the signature.

JS Reading the claims of a JWT

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Why tokens expire: access and refresh tokens

If a token never expired, a stolen one would work forever. So APIs issue two tokens:

  • An access token: short-lived (minutes). It goes in every API request.
  • A refresh token: long-lived (days or weeks), used only to ask the authorization server for a new access token. It travels rarely, so it is much harder to steal in transit.
sequenceDiagram
  participant B as Browser
  participant A as API
  participant S as Auth server
  B->>A: GET /orders (access token)
  A-->>B: 401 token expired
  B->>S: POST /token (refresh token)
  S-->>B: new access token
  B->>A: GET /orders (new access token)
  A-->>B: 200 orders

On a 401 the client refreshes once and replays the original request. The user notices nothing.

The tricky part is concurrency. A dashboard may fire five requests at once; if the token has just expired, all five get a 401, and a naive client would send five refresh requests. Many servers rotate the refresh token on every use, so the second refresh fails and the user is logged out for no reason. The fix is to share one in-flight refresh promise between all callers. This example wraps fetch that way and proves it by counting how many times the stand-in server saw a refresh:

JS A fetch wrapper that refreshes once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All three requests succeed and the server saw one refresh. When the refresh token is rejected, the wrapper stops retrying and surfaces a clear message so the app can send the user to the sign-in page. Note the isRetry flag: without it, a persistent 401 would loop forever.

Where should tokens live?

There is no perfect answer, only trade-offs:

  • In JavaScript memory (a variable): not available to other tabs and lost on reload, but nothing persistent for an attacker to steal later. A good choice for access tokens, paired with a silent refresh when the page loads.
  • localStorage / sessionStorage: survives reloads, but any script on your page can read it, so one XSS bug leaks the token (see Web Storage and XSS, CSRF and Safe DOM Updates).
  • HttpOnly, Secure, SameSite cookie: JavaScript cannot read it, which removes the theft-by-script problem. You then protect against CSRF with SameSite and, where needed, anti-CSRF tokens.

A common modern pattern for browser apps is to keep the refresh token in an HttpOnly cookie (sent only to the token endpoint) and the access token in memory. Whatever you choose, never put long-lived secrets in front-end source code, never log tokens, and always use HTTPS.

OAuth 2.0 in one picture

OAuth 2.0 is the standard that lets an app act on a user's behalf without ever seeing their password. "Sign in with Google" or "let this app read my GitHub repositories" are OAuth flows. Four roles are involved: the user (resource owner), your app (client), the authorization server (where the user logs in, e.g. Google) and the API (resource server). Instead of a password, your app receives a limited, expiring token carrying only the scopes the user approved (for example read:profile).

For browser and mobile apps the recommended flow is the Authorization Code flow with PKCE (pronounced "pixy", Proof Key for Code Exchange). Public clients cannot keep a client secret, so PKCE adds a one-time secret created in the browser for each login attempt:

sequenceDiagram
  participant U as User
  participant App as Your app
  participant S as Auth server
  App->>App: create code_verifier (random) and code_challenge = SHA-256(verifier)
  App->>S: redirect with code_challenge, state, scope, redirect_uri
  U->>S: signs in, approves scopes
  S-->>App: redirect back with code and state
  App->>App: check state matches
  App->>S: POST code + code_verifier
  S-->>App: access token (and refresh token)

The server only issues tokens if the verifier matches the challenge sent at the start, so a stolen code is useless to an attacker.

The browser's part is small. You generate the verifier and challenge, build the authorization URL and later check state. The Web Crypto API does the hashing, and the Base64URL encoding is the same trick you saw for JWTs. This example also checks itself against the official test vector from the PKCE specification (RFC 7636), so you can see the algorithm is right:

JS Generate a PKCE verifier and challenge

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real exchange then looks like this (read-only, because it needs a real server):

JavaScript
// Read-only: on the /callback page
const params = new URLSearchParams(location.search);
if (params.get("state") !== sessionStorage.getItem("oauth_state")) {
  throw new Error("State mismatch: possible CSRF attack");
}

const response = await fetch("https://auth.example.com/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code: params.get("code"),
    redirect_uri: "https://app.example.com/callback",
    client_id: "my-spa",
    code_verifier: sessionStorage.getItem("pkce_verifier"),
  }),
});
const { access_token, refresh_token, expires_in } = await response.json();

Remember these rules of the OAuth flow:

  • Always check state. It ties the callback to the login you started, blocking forged callbacks.
  • Use S256, never the plain method, and never the old implicit flow that put tokens in the URL.
  • Register exact redirect URIs with the provider; they must not be wildcards.
  • Request the smallest scopes you need. Users approve scopes, and APIs enforce them.
  • Use a well-tested library or your provider's SDK for production sign-in. OAuth has many edge cases (token rotation, logout, ID token validation), and a library has already handled them.

Putting it together

A typical browser app does this: sign in through OAuth (code + PKCE), keep the access token in memory and the refresh token in an HttpOnly cookie or a secure store, send Authorization: Bearer on every API call through one wrapper like apiFetch, refresh once on 401, and send the user to sign in again only when the refresh fails. The wrapper is also the right place to add headers and use AbortController timeouts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about a JWT's payload is correct?

    A JWT is signed, not encrypted. Front-end code may read claims such as exp for convenience, but only the server can verify the token.
  2. 2. Why share a single in-flight refresh promise between concurrent requests?

    If five requests all see a 401 and each refreshes, rotating refresh tokens can make the later refreshes fail. One shared refresh serves everyone.
  3. 3. What is the main protection an HttpOnly cookie gives?

    HttpOnly hides the cookie from document.cookie, which stops XSS from stealing it. CSRF still needs SameSite or tokens.
  4. 4. What problem does PKCE solve for browser apps?

    The client sends a hash (code_challenge) first and the original code_verifier later. The server checks they match.
  5. 5. Why does the OAuth callback check the state parameter?

    state is a random value the app creates and later compares. A mismatch means the response may be an attack.

Summary

  • APIs identify callers with session cookies (browser attaches them; watch CSRF) or bearer tokens (your code attaches them; watch XSS).
  • A JWT payload is readable but must be verified by the server; the front end may read exp to plan a refresh.
  • Use short-lived access tokens and long-lived refresh tokens; on a 401, refresh once (share one in-flight promise) and replay the request once.
  • Store access tokens in memory where possible; prefer HttpOnly, Secure, SameSite cookies for long-lived secrets; never keep secrets in source code.
  • OAuth 2.0 Authorization Code with PKCE lets users approve limited scopes without sharing passwords; always verify state and use S256.
  • Prefer a trusted library for real sign-in flows.

Next, learn how to find and fix problems in all these requests: Debugging AJAX.