Stop 12 · Authentication & SecurityTopics · 4/12

Storing Tokens in httpOnly Cookies

Part of the MERN Stack Roadmap

In short

Where you keep a login token decides how easily it can be stolen. Many tutorials use localStorage, but one injected script can read it. httpOnly cookies keep the token out of JavaScript's reach completely.

Keeping tokens in httpOnly, Secure, SameSite cookies stops JavaScript from reading them, which protects them from XSS attacks better than localStorage.

The jaadu places a small golden key into a heavy bank locker drawer and turns the big dial to lock it shut.

Think of it like this

The bank locker

Keeping your gold at home in a drawer (localStorage) is handy, but anyone who gets inside can open it. A bank locker (httpOnly cookie) is used on your behalf: the bank brings it out when you visit, but nobody can carry it off from the lobby. Your React code never touches the token, and neither can an attacker's script.

Watch it happen

Where should the token live?

localStorage

  • Any script on the page can read it, including injected XSS code
  • You must attach it to every request yourself
  • Survives until you delete it

httpOnly cookie

  • JavaScript cannot read it at all
  • The browser sends it automatically to your API
  • Secure, SameSite and maxAge control when it is sent and how long it lasts

Use httpOnly, Secure, SameSite cookies for auth tokens. Add CSRF protection if you allow cross-site requests.

The big ideas

What you need to know

httpOnly

document.cookie cannot see the cookie, so XSS cannot steal the token.

Secure

The cookie is sent only over HTTPS. Turn it on in production.

SameSite

Lax or Strict stops most cross-site requests from carrying the cookie, which blocks most CSRF. Use None plus Secure only when frontend and API are on different sites.

credentials: include

If the frontend and API are on different origins, fetch needs credentials: "include" and the server needs cors({ origin, credentials: true }).

See it in code

Walk through the code

js
1// server/controllers/auth.js2import jwt from "jsonwebtoken";3 4const isProd = process.env.NODE_ENV === "production";5 6export function sendAuthCookie(res, user) {7  const token = jwt.sign({ sub: user.id, role: user.role }, process.env.JWT_SECRET, {8    expiresIn: "15m",9  });10 11  res.cookie("access_token", token, {12    httpOnly: true,13    secure: isProd,14    sameSite: "lax",15    maxAge: 15 * 60 * 1000,16    path: "/",17  });18}19 20export function logout(req, res) {21  res.clearCookie("access_token", { httpOnly: true, secure: isProd, sameSite: "lax", path: "/" });22  res.status(204).end();23}24 25// Reading it in middleware (needs app.use(cookieParser()))26export function requireAuth(req, res, next) {27  const token = req.cookies.access_token;28  if (!token) return res.status(401).json({ message: "Not logged in" });29  try {30    req.user = jwt.verify(token, process.env.JWT_SECRET);31    next();32  } catch {33    res.status(401).json({ message: "Session expired" });34  }35}

1/5Sign a short-lived token with the user id as sub and their role.

Set, clear and read a JWT stored in an httpOnly cookie.

Save yourself the pain

Common mistakes

Oops

Returning the token in the JSON body and also saving it in localStorage "just in case".

Do this instead

Pick the cookie. A copy in localStorage brings back the XSS risk you were avoiding.

Oops

Setting secure: true while testing on http://localhost and wondering why no cookie appears.

Do this instead

Tie secure to NODE_ENV so it is on in production and off on plain HTTP locally.

Oops

Using sameSite: "none" by default.

Do this instead

Start with lax. Use none (with secure) only for a truly cross-site setup, and then add CSRF tokens.

Your mission

Move your token to a cookie

~40 min

Quick check

What does the httpOnly flag protect against?

Go deeper

  1. 1Set the token with res.cookie and the httpOnly, secure and sameSite options.
  2. 2Use cookie-parser in Express and withCredentials in Axios.
  3. 3Clear the cookie on logout.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge