# Move JWTs From localStorage to httpOnly Cookies in an Express API

Yes. The agent sets the token as an httpOnly cookie at sign-in, reads it in the verify middleware, fixes CORS for credentials and adds the sign-out route.

[Run this on Rush](https://cloud.getrush.ai/run/move-jwt-to-httponly-cookies/jsonwebtoken/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The change starts on the server, and the agent reads where the token leaves and re-enters it. In an API like bezkoder/node-js-jwt-auth, `signin` in `app/controllers/auth.controller.js` returns the JWT as `accessToken` in the JSON body, and `verifyToken` in `app/middleware/authJwt.js` reads it back from the `x-access-token` header. Front ends written for this API, such as bezkoder/react-redux-jwt-auth, keep the whole sign-in response in `localStorage` and attach the header from there, which is the exposure the issue is about: any script running on the page can read the token. An `httpOnly` cookie cannot be read by script at all.

Three facts in the repository decide what has to change besides one `res.cookie` call. First, Express can set cookies but does not parse them: without the `cookie-parser` package, which is not in `package.json`, `req.cookies` is `undefined` and reading a property from it throws. The agent adds that one dependency. Second, `server.js` configures `cors` with `origin: "http://localhost:8081"` and nothing else. A browser will not send or accept cookies on a cross-origin call unless the response carries `Access-Control-Allow-Credentials: true`, so the agent adds `credentials: true`; the origin is already a single named one, which that mode requires. Third, there is no sign-out route, because until now the client signed out by deleting its own storage. Script cannot delete an `httpOnly` cookie, so the agent adds `POST /api/auth/signout`, which clears it with the same attributes it was set with.

The cookie's attributes are chosen from what the code already says. The token is signed with `expiresIn: 86400`, so the cookie gets the matching `maxAge`. It is `httpOnly`, `sameSite: "lax"`, and `secure` when the app runs in production. The agent spells out what `lax` relies on: the page on port 8081 and the API on port 8080 are the same site, since a site ignores the port, so the cookie travels on their calls. Deployed on two unrelated domains it would not, and the alternative, `SameSite=None`, brings cross-site request forgery back into scope. Cookies are attached by the browser automatically, so the agent adds an `Origin` check on methods that change state and says that a CSRF token, if you want one, is a decision for the team.

It does not break the clients that are live today. The middleware looks for the cookie first and falls back to the header, and sign-in keeps returning `accessToken` in the body behind a config flag that defaults to on. The pull request states that this is step one of two and that the protection is only complete once front ends send requests with credentials, stop storing the token, and the flag is turned off. To test, the agent installs MariaDB from system packages, creates the `testdb` database the config names, seeds the three roles that sign-up needs, starts the server and drives it with a cookie jar: sign in, call `/api/test/user` with only the cookie, send a preflight and read the headers, sign out, call again.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "An issue labelled security asks to stop exposing the JWT to browser JavaScript in this Express API. Read package.json, server.js and everything under app. Report where the token is returned to the client, where it is read back, how CORS is configured (including any headers set by hand in route files), whether anything parses cookies today, and whether a sign-out route exists. Change sign-in to also set the token as a cookie that is httpOnly, has a SameSite value you justify from the origins in the CORS config, is Secure in production, and expires with the token. Make the verify middleware read the cookie first and fall back to the existing header so current clients keep working. Add whatever is needed to parse cookies, enable credentials in CORS without widening the allowed origin, add a sign-out route that clears the cookie with matching attributes, and add an Origin check for state-changing methods. Keep returning the token in the sign-in body behind a config flag that defaults to on, and document the second step that turns it off. Do not change the token's contents, lifetime, signing or the user fields in the response. Install the database server the config expects from system packages (no Docker), create its database, seed what sign-up requires, run the server and verify with real HTTP calls: cookie attributes on sign-in, a protected route with only the cookie, the same route with only the header, the CORS preflight headers, and sign-out. Add those as tests using only what Node provides. Open a pull request with the header dumps, the test output, and a checklist of the changes each front end must make.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request touches `server.js` for the cookie parser and the `cors` options, the auth controller for the cookie and the new sign-out handler, `authJwt.js` for the lookup order, the auth routes file, the config for the flag, and `package.json` for one new dependency. The description quotes the `Set-Cookie` line from a real sign-in so a reviewer can read the attributes as a browser would receive them, and the preflight response showing the credentials header beside the unchanged allowed origin.

The tests cover both transports because both are live after this merge: a protected route answers with only the cookie and with only the header, and answers 403 with neither. After sign-out the cookie-only call is refused. A reviewer should check two things in the diff that tests cannot fully show: that the cookie is cleared with the same path and attributes it was set with, since a mismatch leaves it in the browser, and that nothing logs the cookie header.

The front-end checklist is part of the result, since the server change alone protects nobody. For each client it says to send requests with credentials (`withCredentials` in axios, `credentials: "include"` in fetch), to stop writing the token to `localStorage` while still keeping the user's name and roles for the UI, to call the sign-out route, and to drop the header. The last item names the flag to switch off and the fallback branch to delete once every client has shipped.

## Run it on every GitHub issue labelled security

Add an automation to the Project in the console with a `github` trigger on `issues.labeled` and `security` in its `labels`. The saved prompt holds the method: map where the token travels, cookie attributes justified from the configured origins, both transports during the transition, real HTTP verification, a front-end checklist. The labelled issue is placed after the prompt as the event, so the reporter's notes on which clients exist reach the agent.

Only an owner, member or collaborator of the repository can fire a `github` trigger, and issues opened or labelled by bots never do. If the front ends live in their own repositories, each gets its own Project; the checklist from this run becomes the body of the issue you label there.

## Why run it on Rush?

Cookie behaviour is decided by headers on the wire, and the only trustworthy check is to run the server and read them. The agent does that in a sandbox with its own database, so it can sign in, replay requests with and without the cookie, send a preflight and paste the actual responses into the pull request. The commands are kept with their output in the session's transcript at `GET /o/{org}/sessions/{id}/messages`, which is what a security reviewer will want to see.

It also keeps a two-step rollout honest. The run delivers step one with both transports tested and a written list for step two. When the front ends have shipped, a follow-up message to the same session, or a new run on the merged branch, removes the fallback and the body field and reruns the same checks, so the second pull request is small and its test output is directly comparable with the first.

## Frequently asked questions

### Why keep the header working at all?

Because the API and its front ends rarely deploy at the same moment. If the server stopped reading the header on merge, every signed-in user of an older front end would start getting 403. The fallback and the body field are removed in a second pull request once clients send cookies.

### Is SameSite=Lax enough against CSRF?

It stops the browser from attaching the cookie to cross-site POST requests, which covers the common case. The agent adds an `Origin` check on state-changing methods as a second measure. Whether you also want a CSRF token depends on your browsers and threat model, and the pull request leaves that choice to you.

### What if my front end and API are on different domains?

Then they are different sites and a `Lax` cookie is not sent on calls between them. The options are to serve the API under the same registrable domain as the front end, or to use `SameSite=None; Secure` with stronger CSRF protection. The agent reads the configured origins and tells you which case you are in.

### Does the front end still know who is signed in?

Yes. The sign-in response keeps `id`, `username`, `email` and `roles`, and the client may store those. Only the token moves out of script's reach.

## More jsonwebtoken jobs

- [Add Refresh Tokens to an Express API That Uses jsonwebtoken](https://getrush.ai/run/add-refresh-tokens/jsonwebtoken/)

## More jobs like this: Turn a Linear label into a PR

- [Remember Window Size and Position Between Launches in a Tauri App](https://getrush.ai/run/persist-window-state/tauri/)
- [Plan a Linear Issue Against a Django Codebase](https://getrush.ai/run/plan-linear-issues/django/)
- [Plan a Linear Issue Against a Go Codebase](https://getrush.ai/run/plan-linear-issues/go/)
- [Plan a Linear Issue Against a Next.js Codebase](https://getrush.ai/run/plan-linear-issues/nextjs/)
- [Plan a Linear Issue Against a Ruby on Rails Codebase](https://getrush.ai/run/plan-linear-issues/rails/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
