A NestJS 12 app on @nestjs/authentication signs every customer out on each deploy. What is missing, and what must its replacement session store guarantee?
answer
- where state lives by default
- the production guard reads one variable
- registerSource from the constructor
- conditional update, counted delete
basics
~20 sNo SessionStore is registered, so sessions live in the in-memory default; the startup check only refuses that when NODE_ENV is production. Register a store with AuthenticationStorage.registerSource(), whose touchSession() is a conditional update and deleteSession() reports its row count.
solid answer
~50 sIn NestJS 12's `@nestjs/authentication`, a contract with no registered store falls back to memory, so a restart signs everyone out and instances don't share sessions. The module refuses to start that way only when `NODE_ENV` is `production` and `allowInMemoryStorage` isn't set; otherwise it just logs that it is using in-memory stores. The fix is a singleton `@Injectable()` that implements `SessionStore`, injects `AuthenticationStorage` and calls `storage.registerSource({ sessions: this })` in its constructor. The contract's hard rules: `touchSession()` is one conditional update that only moves `lastActiveAt` forward on a row that still exists, so a request can't resurrect a signed-out session; `deleteSession()` is one delete that resolves whether it removed the row, so only one of two racing rotations or sign-outs wins. `getSession()` may return expired rows, and optional fields come back absent, not `null`. Prove it with `authenticationStoreContract()` and `concurrent: true`.
code
plaintext · 2 linesLOG [AuthenticationModule] AuthenticationRegistry: providers SessionAuth
LOG [AuthenticationModule] AuthenticationStorage: in-memory stores (the default: state is lost on restart and not shared between instances)go deeper
Recall that sessions live in memory until a store registers, and that a store registers itself with registerSource() from its constructor.
Explain the production guard's NODE_ENV condition, what allowInMemoryStorage does, and which store methods must be single conditional statements.
Diagnose the deploy sign-out from the startup log, then show how the touch and delete races resurrect or double-rotate sessions and how the contract tests catch them.
Treat NODE_ENV and the contract suite as release gates for every service using the package, and decide who owns the store tables and their migrations.
## The symptom and its cause `@nestjs/authentication` in NestJS 12 never talks to your database. It describes what it keeps as six store interfaces (`SessionStore`, `RefreshTokenStore`, `MfaStore`, `MagicLinkStore`, `OidcStateStore` and `EmailTokenStore`) and expects the application to implement the ones its features use. **A contract with no registered store falls back to an in-memory default**, which loses everything on restart and is not shared between instances. Sessions in process memory explain both symptoms at once: everyone is signed out on each deploy, and with two instances behind a balancer a customer seems signed in on one request and anonymous on the next. The module does try to stop this. When storage locks during `AuthenticationModule` initialization, it computes which contracts the configured features use (a registered `SessionCookieProvider` uses `sessions`) and, if one has no store, refuses to start, but **only when `NODE_ENV` is `production`** and `allowInMemoryStorage` is not `true`. The error names the missing interface and the fix: ```plaintext AuthenticationStorage: no store is registered for `sessions` (SessionStore), and NODE_ENV is "production": in memory, sessions would be lost on restart and not shared between instances. ... ``` Outside production it only logs `AuthenticationStorage: in-memory stores (the default: state is lost on restart and not shared between instances)`. So the usual diagnosis is one of two things: the deployment never set `NODE_ENV=production`, or someone set `allowInMemoryStorage: true` to get past the error. ## Registering a real store A store is an ordinary **singleton** `@Injectable()` class that implements `SessionStore` (its six methods are `getSession()`, `createSession()`, `touchSession()`, `deleteSession()`, `listUserSessions()` and `deleteUserSessions()`), injects `AuthenticationStorage`, and registers by contract name in its constructor: ```typescript constructor(storage: AuthenticationStorage) { storage.registerSource({ sessions: this }); } ``` The registry checks each store's shape immediately, refuses a second store for the same contract unless `replace: true` is passed, and after the lock logs where each kind of state lives, for example `AuthenticationStorage: SqlSessionStore (sessions)`. Method names never repeat across contracts, so one class can implement all six, or several classes can split them. ## What the session store must guarantee Most methods are plain reads, inserts and deletes. Two are not, because a race between them decides whether a sign-out sticks: | Method | Must be | Race it prevents | | --- | --- | --- | | `touchSession(id, lastActiveAt)` | one conditional update of an existing row, moving `lastActiveAt` forward only | a request that read the session before a sign-out writing it back to life | | `deleteSession(id)` | one delete that resolves `true` only if this call removed the row, from its row count | two rotations, or a rotation and a sign-out, both believing they won | In SQL terms `touchSession()` is `UPDATE ... SET last_active_at = ? WHERE id = ? AND last_active_at < ?`, never an upsert and never a read followed by a write. The other rules from the interface's doc comments: - `getSession()` returns the record or `undefined`; it **may return expired sessions**, because `SessionService` checks expiry with its own clock. - Optional fields come back **absent, never `null`**. - `createSession()` is a plain insert of a fresh id, and a good place to delete expired rows so the table stays bounded. - `getSession()` may set `extra` to the user read in the same query, which `validate()` then receives; `extra` is never stored. - `touchSession()` is **best-effort**: if it rejects, the request goes on, a `session-touch-failed` event is published, and the session simply goes idle at its previous deadline. None of these methods takes your transaction: authentication state is written on its own, never inside a business transaction. ## Proving it before the next deploy 1. Implement the interface and register it from the constructor. 2. Run `authenticationStoreContract()` from `@nestjs/authentication/testing` against the store. It returns test cases for any runner; `concurrent: true` adds the races (a sign-out racing a request, parallel deletes of one session, a rotation racing a sign-out), and they should run against a real database with a connection pool, where a read-then-write store fails. 3. Set `NODE_ENV=production` in every deployed environment and remove any `allowInMemoryStorage: true`, so the next missing store fails the boot instead of the users. 4. Check the startup log for the store's class name rather than the in-memory line. ## Why not just allow memory? `allowInMemoryStorage: true` is legitimate for a demo or a single-instance tool where signing everyone out on restart is acceptable. In a deployed API it trades a visible startup failure for invisible session loss, and with several instances it breaks sign-in outright.
- Why must touchSession() never be an upsert or a read followed by a write?A request can read a session, then a sign-out deletes it, then the request records activity. An upsert or a read-then-write would insert the row again and bring the signed-out session back. A single `UPDATE ... WHERE id = ? AND last_active_at < ?` touches only a row that still exists and only moves the timestamp forward.
- What does deleteSession() returning a boolean buy you?Session rotation deletes the old row and creates a new one. If two rotations, or a rotation and a sign-out, hit the same session at once, the row count of one delete statement tells exactly one caller it won. `SessionService.rotate()` relies on that, so a store that always resolves `true` lets both proceed.
- When is allowInMemoryStorage: true acceptable?For a demo or a single-instance internal tool where losing every session on restart is tolerable. In a deployed API it hides the problem the production guard exists to surface: every deploy signs users out, and multiple instances cannot see each other's sessions.
- The package writes sessions to the application's database by itself.
- The production check fails startup in every environment, not only production.
- touchSession() can safely be an upsert of the whole session row.
- deleteSession() can resolve true whether or not a row was removed.
- getSession() must filter out expired sessions itself.
- A failed touchSession() fails the user's request.
Assumes NestJS 12: the first-party @nestjs/authentication package declares @nestjs/common and @nestjs/core 12 as peer dependencies and is taught by the v12 security docs.