# Move Express Sessions from MemoryStore to MongoDB in a Node.js App

Yes. An agent moves Express sessions from the in-memory store into the MongoDB the app already uses, with a TTL index, expiry and the first unit tests.

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

## What the agent does

The agent starts with how sessions are configured today, because the store is only one of the settings that need to change together. In an app like OWASP/NodeGoat, `server.js` calls `app.use(session({...}))` with `secret: cookieSecret`, `saveUninitialized: true` and `resave: true`, and no `store`, so `express-session` 1.15.6 falls back to its in-memory store: every session dies on restart, memory grows with each visitor because `saveUninitialized: true` writes a session for anonymous requests, and a second process cannot share logins. The secret comes from `config/env/all.js` as a hard-coded `cookieSecret`, next to `db`, which reads `MONGODB_URI` with a `mongodb://localhost:27017/nodegoat` default. Across `app/routes/`, the handlers rely on `req.session.userId`: `session.js` sets it on login and signup, calls `req.session.regenerate` in one path and `req.session.destroy` on logout, and `isLoggedInMiddleware` and `isAdminUserMiddleware` gate every protected route on it.

It then checks the obvious package before choosing it. The app connects with the `mongodb` driver at 2.2.36 in `package-lock.json` (`^2.1.18` in `package.json`), callback style, and hands the connected `db` into seven data-access classes under `app/data/`. `connect-mongo` declares the driver as a peer dependency at 5.0.0 or newer, so installing it means either a second driver copy or upgrading every DAO to the promise-based API, a change far larger than the issue asks for. The agent reports that conflict in the pull request and takes the smaller road: an `express-session` store of its own, since the store contract is four methods, `get`, `set`, `destroy` and `touch`, over the connection the app already has.

The new file, `app/session-store.js`, extends `session.Store`, takes the connected `db` from the `MongoClient.connect` callback in `server.js`, and keeps sessions in a `sessions` collection with the session id as `_id`, the session object as `session` and an `expires` date. It creates a TTL index on `expires` with `expireAfterSeconds: 0` at startup so MongoDB removes expired documents itself, implements `touch` so `resave: true` can become `resave: false` without losing the rolling expiry, and computes `expires` from `cookie.maxAge` with a fourteen-day default when the cookie has none. In `server.js` the agent passes the store, turns `saveUninitialized` off so anonymous page views no longer write a document, and sets `cookie.httpOnly: true` and a `maxAge`, which the file's own commented-out block already marks as the intended fix. The hard-coded secret is left in place but called out in the description with `SESSION_SECRET` as the suggested environment variable, because changing it invalidates every live login and is the owner's call.

The proof has two parts. The repository's `Gruntfile.js` already points `mochaTest:unit` at `test/unit/*.js`, a directory that does not exist, so `grunt test` currently runs nothing; the agent creates `test/unit/session-store.js` with Mocha and `should`, both already in `devDependencies`, and starts a real `mongod` through `mongodb-memory-server` in a `before` hook, then tests set-then-get, destroy, touch extending `expires`, and a `get` on an unknown id returning nothing. Then it starts the app against the same server, logs in through the browser in its sandbox with a seeded user from `artifacts/db-reset.js`, restarts the Node process, reloads `/dashboard`, and shows the session survived, which is the behaviour the memory store could never give.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Move this Express app's sessions out of the default in-memory store into the MongoDB it already connects to. Read server.js, config/config.js, config/env/all.js, package.json, package-lock.json, app/routes/session.js and the other files under app/routes that use req.session first. Check whether connect-mongo's peer dependency range includes the mongodb driver version in the lockfile; if it does not, write a small express-session Store over the existing connection with a TTL index on an expires field and a touch method, and explain the choice. Pass the store in server.js, set saveUninitialized to false, resave to false, and an httpOnly cookie with a maxAge. Add Mocha unit tests for the store under test/unit, where the Gruntfile already looks, using an in-memory mongod. Start the app, log in, restart the process and show the session survives. Open a pull request that links the issue.",
  "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

What comes back is a pull request on its own branch adding `app/session-store.js` and `test/unit/session-store.js`, editing `server.js` for the store and cookie settings, and adding `mongodb-memory-server` to `devDependencies` in `package.json` and `package-lock.json`. The seven DAO files, the routes and the Mongo driver version are untouched, so the diff stays readable in one sitting.

The description explains the connect-mongo decision in a paragraph with the driver version from the lockfile and the peer range it was checked against, lists the four store methods and the TTL index, shows the Mocha output for the new unit tests, and shows the login-restart-reload sequence with screenshots from the transcript at `GET /o/{org}/sessions/{id}/messages`. It also names the hard-coded `cookieSecret` as the next thing to fix, with the one-line change to read it from the environment.

Before merging, a reviewer checks the `expires` arithmetic against the cookie `maxAge` they want, decides whether `saveUninitialized: false` affects any flow that relied on an anonymous session, and plans the secret rotation, since the first deploy with a new secret signs everyone out.

## Run it on every Linear issue labelled agent

In the console, an automation with a `linear` trigger on `linear.issue.labeled` and the label `agent` starts one run per labelled issue in the Project that holds the app, with the issue text as its context. An issue that reads "sessions are lost on every deploy, move them to Mongo" is enough: the trigger appends the issue after the prompt and the agent finds `app.use(session(...))` and the driver version on its own. Changes made by an app integration never fire the trigger, so the agent's own activity on the issue starts nothing.

From your own server, the same run is one `POST /o/{org}/sessions` per issue with this body, the repository in `resources` and the issue's `https://linear.app/<workspace>/issue/<ID>` URL there too, read through your Linear connection into the prompt. Send a `request_id`, a UUID v5 of the issue id, so a redelivered event does not start a second run.

## Why run it on Rush?

The textbook answer, install connect-mongo and pass `store`, fails on this app at `npm install` because of a peer dependency range, and the second textbook answer, upgrade the driver, rewrites seven files of callback code. Knowing which road to take requires reading the lockfile, and the right small store needs a TTL index and a `touch` method that a rushed version leaves out. The agent does the reading first and writes the reasons into the pull request.

On Rush the app, a real `mongod` and the browser all run in the agent's sandbox, so the restart test that proves the feature happens where it cannot disturb anyone's database, and the Mocha output and the screenshots stay in the transcript. A Linear label becomes a pull request with its evidence attached, and several labelled issues can run at once, each in its own sandbox with its own branch.

## Frequently asked questions

### Why not just use connect-mongo?

Because its peer dependency on the `mongodb` driver starts at 5.0.0 and this app runs 2.2.36 with callback-style DAOs. The agent checks that range against the lockfile before deciding; on an app with a current driver it installs connect-mongo and passes `clientPromise` instead of writing a store. Either way the description says which it chose and why.

### Will existing logged-in users be signed out?

Once, at deploy, because the memory store's sessions live in the old process and cannot be migrated. After that, sessions survive restarts and deploys, which is the point. Changing the hard-coded secret, which the pull request recommends but does not do, signs everyone out a second time, so plan the two together.

### How are expired sessions cleaned up?

By MongoDB. The store writes an `expires` date on every `set` and `touch` and creates a TTL index on that field with `expireAfterSeconds: 0`, so the server removes expired documents on its own schedule and the app runs no cleanup job. The unit test checks the index exists after the store starts.

### Does it need Docker for the tests?

No. The unit tests start a real `mongod` through `mongodb-memory-server`, which downloads the binary once, so `grunt test` runs the same way on a laptop, in CI and in the Rush sandbox. The repository's own `e2e-test.yml` keeps using a Mongo container for Cypress and is not changed.

## More Node.js jobs

- [Set Up npm Trusted Publishing for a Node.js Package](https://getrush.ai/run/add-npm-trusted-publishing/nodejs/)
- [Add Rate Limiting to a Node.js Login Route](https://getrush.ai/run/add-rate-limiting/nodejs/)
- [Add Security Headers to a Node.js App](https://getrush.ai/run/add-security-headers/nodejs/)

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

- [Add Kubernetes NetworkPolicies to a Multi-Service App](https://getrush.ai/run/add-network-policies/kubernetes/)
- [Add NetworkPolicies to a Kustomize App](https://getrush.ai/run/add-network-policies/kustomize/)
- [Add a NetworkPolicy Option to a Helm Chart](https://getrush.ai/run/add-network-policy/helm/)

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