# Add Refresh Tokens to an Express API That Uses jsonwebtoken

Yes. The agent adds a stored, rotating refresh token and a refresh route beside your access tokens, and proves expiry, rotation and reuse against a real database.

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

## What the agent does

The agent reads how tokens are made and checked today. In an API like bezkoder/node-js-jwt-auth, `app/controllers/auth.controller.js` signs `{ id: user.id }` with `jwt.sign`, HS256 and `expiresIn: 86400`, using a secret that is a string literal in `app/config/auth.config.js`. `app/middleware/authJwt.js` reads the `x-access-token` header and calls `jwt.verify`; on any error it answers 401 with one fixed message. That last detail shapes the work: `jsonwebtoken` reports an expired token as `TokenExpiredError` and a forged one as `JsonWebTokenError`, but the middleware flattens both, so a client cannot tell when a refresh would help. There are two auth routes, `POST /api/auth/signup` and `POST /api/auth/signin`, and no sign-out. `package-lock.json` is listed in `.gitignore`, so the agent records the versions `npm install` resolved, since no lockfile pins them.

To run anything it needs the database the code expects. `app/config/db.config.js` points Sequelize at MySQL on localhost with user `root`, a fixed password and a database named `testdb`. The sandbox has no Docker, so the agent installs MariaDB from system packages, sets that password and creates the database. The first sign-up on an empty database then shows a problem that is not about tokens. `server.js` calls `db.sequelize.sync()`, and the `initial()` function that would insert the three roles is only called from a commented-out block, so the `roles` table is empty. Sign-up inserts the user, `user.setRoles([1])` fails its foreign key, nothing catches that rejection, and current Node ends the process on it. The user row stays behind without a role. The agent seeds the roles in its own test database, reports the crash, and does not fold a fix into this pull request unless the issue asks.

The design it implements is the conservative one. A refresh token is an opaque random string from `crypto.randomBytes`, not a second JWT. Only its SHA-256 hash is stored, in a new `refreshTokens` model that belongs to the user and has an expiry and a revoked time. Sign-in returns it beside `accessToken`. `POST /api/auth/refreshtoken` looks the hash up, refuses unknown or expired tokens, marks the presented token revoked, and returns a new access token with a new refresh token. Presenting a token that was already rotated is treated as theft: every live refresh token of that user is revoked. A sign-out route revokes the current one. The middleware gains one branch so that an expired access token answers 401 with a distinct code the client can act on.

How the schema changes matters in this codebase. `sync()` creates tables that are missing and leaves existing ones as they are. A new `refreshTokens` table therefore appears on the next start with no migration, while a column added to the `users` model would not appear and would break sign-in with an unknown-column error. The agent keeps everything in the new table for that reason. There is no test script (`npm test` only echoes an error), and `server.js` starts listening without exporting the app, so the agent writes tests with Node's built-in runner that start the server as a child process and call it over HTTP, adding no dependency.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "A Linear issue labelled auth asks for refresh tokens in this Express API, which signs access tokens with jsonwebtoken. Read package.json, server.js, and everything under app first: config, models, controllers, middleware and routes. Describe how a token is signed and verified today, its lifetime, which header carries it, and what the middleware answers for an expired token versus an invalid one. Install the database server this app is configured for from system packages (no Docker), create the user and database from the config, start the app and exercise sign-up and sign-in on an empty database; report anything that fails before you change code and seed whatever is needed in your test database only. Implement refresh tokens as opaque random values stored hashed in their own table with an owner, expiry and revocation time; rotate on every use; treat reuse of a rotated token as compromise and revoke that user's other refresh tokens; add a refresh route and a sign-out route; make the access and refresh lifetimes config values and keep the current access lifetime as the default unless the issue names another. Make the verify middleware answer an expired access token with a distinct, documented error code while keeping the status. Check how this app applies schema changes and choose a storage design that works with it without altering existing tables. Do not move the signing secret or change existing response fields. Add tests that run against the real database: expiry with a short lifetime, a normal refresh, reuse of a rotated token, an unknown token and sign-out. Open a pull request with the request and response of each new route, the test output, and the findings you did not fix.",
  "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 adds `app/models/refreshToken.model.js` and registers it in `app/models/index.js`, extends the auth controller and routes with refresh and sign-out, adds one branch to `authJwt.js`, and puts the two lifetimes in `auth.config.js`. Sign-in's response gains a `refreshToken` field and loses nothing, so existing clients keep working. The description documents each new route with an example request and the answers for success, unknown token, expired token and reused token.

The test output is the proof of the security behaviour. It shows a token signed with a lifetime of a few seconds being refused after that time with the new error code, a refresh returning a different pair, the old refresh token being refused on second use, and the token issued by the first refresh being refused too after that reuse. A reviewer should read the reuse test closely, and check in the model that the raw token is never written to the table or to a log.

A findings section lists what the agent saw and left alone: the sign-up crash on a database with no roles, the signing secret committed in `auth.config.js`, the `allowInsecureKeySizes` flag on `jwt.sign`, and the absence of a lockfile. It also states the consequence of the chosen default. With the access lifetime left at 24 hours the new route adds little; shortening it is one config value, and front ends that do not call the refresh route will then be signed out at that interval.

## Run it on every Linear issue labelled auth

Add an automation to the Project in the console with a `linear` trigger on `linear.issue.labeled` and `auth` in its `labels`. The saved prompt is the method: read the current token flow, stand up the real database, storage that fits how the app applies schema changes, tests for expiry and reuse, findings listed. The issue is placed after the prompt as the event and supplies the specifics, such as the lifetimes your security review settled on.

The trigger needs a Linear connection for the member who last changed the automation, made in the console under Settings → Connections, and it fires only when the person who applied the label is in your Rush org. If several services need the same change, give each its own Project and automation so every run opens its pull request in the right repository.

## Why run it on Rush?

Refresh-token logic is judged on what it does with the wrong input: an expired token, a replayed one, one that was never issued. Those cases need a running server and a real table, because the interesting failures are in the queries and the timing. The agent installs the database, runs the server and drives it over HTTP in its own sandbox, so your development database is never the test bed and the commands and their output are kept in the session's transcript.

The same run surfaces problems next to the task that a narrower edit would step over. Here that is a sign-up that brings the process down on a fresh database. It is found only by starting from empty, which is what a new sandbox does every time and what a long-lived laptop setup never does. The finding arrives in the pull request with the exact error, ready to become its own issue.

## Frequently asked questions

### Why is the refresh token not a JWT?

A refresh token has to be revocable, so the server must look it up on every use anyway. An opaque random value stored as a hash gives that with less to get wrong: there is no second signing key or algorithm to manage, and a leaked database row cannot be replayed. The access token stays a JWT so ordinary requests need no lookup.

### Does this change my existing sign-in response?

It adds a `refreshToken` field and keeps `id`, `username`, `email`, `roles` and `accessToken` as they are. Clients that ignore the new field behave as before until you shorten the access lifetime.

### Do I need database migrations for this?

That depends on how your app applies its schema, and the agent checks before choosing. In an app that calls Sequelize's `sync()` at start, a new table is created automatically and existing tables are never altered, so it stores everything in a new table. If your project has a migrations directory, it writes a migration in the same style.

### Can it also move the tokens into cookies?

It can, but as a separate change. Cookie transport touches CORS, the front ends and CSRF protection, and reviewing it together with rotation logic hides both. Ask for it in its own issue once this one is merged.

## More jsonwebtoken jobs

- [Move JWTs From localStorage to httpOnly Cookies in an Express API](https://getrush.ai/run/move-jwt-to-httponly-cookies/jsonwebtoken/)

## The same job on other stacks

- [Add Refresh Token Rotation to a NextAuth.js App](https://getrush.ai/run/add-refresh-tokens/next-auth/)
- [Add Refresh Tokens to a FastAPI App on SQLModel](https://getrush.ai/run/add-refresh-tokens/sqlmodel/)
- [Add Refresh Tokens to an Axum JWT API](https://getrush.ai/run/add-refresh-tokens/axum/)
- [Add Refresh Tokens to a Gin JWT API](https://getrush.ai/run/add-refresh-tokens/gin/)

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

- [Add Related Posts to an Astro Blog](https://getrush.ai/run/add-related-posts/astro/)

## 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/)
