Tokens in memory, Authorization headers & 401

Keep tokens out of reach

Lesson 14 of 20 · 12 min · Module 4: Requests you can trust

Some apps receive an access token after signing in and send it with every request. Where that token is kept decides how much a single XSS bug can steal.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Choose where an access token is kept
  • Send tokens in the Authorization header
  • Handle sessions that end

The idea

Everything in localStorage or sessionStorage can be read by every script on the page, including injected ones, and localStorage keeps it even after the tab is closed. A token kept in a variable inside a closure disappears on reload and cannot simply be copied by other scripts. Send it in the Authorization: Bearer … header, never in the address, and when the server answers 401, forget it and ask the person to sign in again.

function createCounter() {
  let count = 0; // only the returned function can see it
  return () => ++count;
}

01Storage is open to every script

localStorage is convenient, and that is the problem: one injected script can copy every token stored there and use it from anywhere, long after the page was closed.

02Cookies or memory

For an ordinary website, an HttpOnly, Secure, SameSite cookie set by the server is the safest home for a session. When an app must use tokens, keep them in memory inside a closure, make them short-lived, and renew them through the server. An injected script can still misuse a page while it runs, so XSS must be fixed regardless.

function createSession() {
  let token = null; // only these functions can see it
  …
}

03401 means start again

An expired or revoked token earns a 401 Unauthorized answer. Forget the token at once, show the sign-in form, and never keep retrying the same request.

Your turn

Rewrite createSession(): keep the token in a variable inside the function instead of localStorage; request(url) sends the request to url unchanged, with the header Authorization: Bearer <token> while signed in and without it otherwise; when the answer is 401, forget the token and throw new Error('signed-out'); signOut() forgets the token.

What the checks look for

  • Signing in shows the name
  • The token stays out of storage
  • Requests carry the token in the Authorization header
  • The token never appears in an address
  • A 401 answer ends the session
  • Signing out forgets the token
Try it in the editor →

Take this with you

Keep tokens in memory or in HttpOnly cookies, send them in headers, and forget them on 401.

Go a little further

Sign people out automatically after 15 minutes without a request, and tell them why.

Learn Web Security Foundations for free

20 short lessons with real code and instant checks.

See the whole course →