auth-service.tsmiddleware.ts
Chat
JWT Token Refresh: Design & Rollout
Overview
Our API gateway authenticates every request with a short-lived JWT access token. Until now, an expired token meant an immediate
401 — even when the user still held a valid refresh token. This document describes the silent-refresh flow we just shipped and how we're rolling it out.The Problem
Token validation ran before any refresh logic, so the middleware rejected expired tokens outright:
- A request arrives with an expired access token
validateToken()throwsTokenExpiredError- The catch block returns
401—refreshToken()is never reached
The result was users getting logged out whenever an access token lapsed mid-session.
The Fix
The middleware now catches
TokenExpiredError specifically and attempts a silent refresh before rejecting. On success it reissues an access token and continues the request; on failure it falls back to 401.- Transparent — valid sessions never see an interruption
- Safe — a missing or invalid refresh token still returns
401 - Cheap — refresh only runs on the expiry path, not on every request
Testing
The refresh path is covered end to end:
| Scenario | Expected |
|---|---|
| Valid token passes through | 200 |
| Expired token, valid refresh | 200 + new access token |
| Expired token, invalid refresh | 401 |
| Malformed token | 401 |
Rollout & Monitoring
- Ship behind the
silent_refreshflag at 5% of traffic - Watch the
auth.refresh.successandauth.refresh.failurecounters - Alert if the failure rate exceeds 2% over any 5-minute window
- Ramp to 100% once metrics hold steady for 24 hours