Fix TokenExpiredError: jwt expired in Express
This error occurs when a JWT token's exp claim is in the past, meaning the token has expired. The jsonwebtoken library throws TokenExpiredError during verification. Fix it by implementing token refresh logic, returning a clear 401 response, and ensuring your token expiration times are appropriate for your use case.
Reading the Stack Trace
Here's what each line means:
- at /app/node_modules/jsonwebtoken/verify.js:152:21: The jsonwebtoken verify function detected the token's exp claim is in the past and threw TokenExpiredError.
- at verifyToken (/app/src/middleware/auth.js:15:16): Your auth middleware at line 15 calls jwt.verify() without handling the TokenExpiredError case separately.
- at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5): Express is executing the auth middleware layer before the route handler, and the error propagates up the stack.
Common Causes
1. Token expiration too short
The JWT is signed with a very short expiresIn value, causing tokens to expire before users can reasonably complete their session.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, process.env.JWT_SECRET, {
expiresIn: '5m' // Too short for most use cases
});
2. No token refresh mechanism
The application issues a single token with no way to refresh it, forcing users to re-authenticate when the token expires.
function verifyToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(403).json({ error: 'Invalid token' });
}
}
3. Clock skew between servers
The server that issued the token and the server verifying it have different system clocks, causing premature expiration.
// Server A issues token at 10:00:00 with 1h expiry
// Server B's clock is 2 hours ahead, sees token as expired
jwt.verify(token, secret); // TokenExpiredError
The Fix
Handle TokenExpiredError separately from other JWT errors, returning a 401 with a TOKEN_EXPIRED code so the client knows to request a new token via the refresh endpoint. Add clockTolerance to handle minor clock skew between servers.
function verifyToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(403).json({ error: 'Invalid token' });
}
}
function verifyToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET, { clockTolerance: 30 });
next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({
error: 'Token expired',
code: 'TOKEN_EXPIRED',
expiredAt: err.expiredAt
});
}
res.status(403).json({ error: 'Invalid token' });
}
}
Testing the Fix
const jwt = require('jsonwebtoken');
const request = require('supertest');
const express = require('express');
const SECRET = 'test-secret';
function createApp() {
const app = express();
app.use((req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
req.user = jwt.verify(token, SECRET, { clockTolerance: 30 });
next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
}
res.status(403).json({ error: 'Invalid token' });
}
});
app.get('/api/profile', (req, res) => res.json({ user: req.user }));
return app;
}
describe('JWT auth middleware', () => {
it('returns 401 with TOKEN_EXPIRED for expired tokens', async () => {
const expired = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '-10s' });
const res = await request(createApp())
.get('/api/profile')
.set('Authorization', `Bearer ${expired}`);
expect(res.status).toBe(401);
expect(res.body.code).toBe('TOKEN_EXPIRED');
});
it('returns 200 for valid tokens', async () => {
const valid = jwt.sign({ userId: 1 }, SECRET, { expiresIn: '1h' });
const res = await request(createApp())
.get('/api/profile')
.set('Authorization', `Bearer ${valid}`);
expect(res.status).toBe(200);
expect(res.body.user.userId).toBe(1);
});
it('returns 401 when no token is provided', async () => {
const res = await request(createApp()).get('/api/profile');
expect(res.status).toBe(401);
});
});
Run your tests:
npx jest --testPathPattern=jwt
Pushing Through CI/CD
git checkout -b fix/express-jwt-expired-error,git add src/middleware/auth.js src/__tests__/jwt.test.js,git commit -m "fix: handle TokenExpiredError with 401 and TOKEN_EXPIRED code",git push origin fix/express-jwt-expired-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx jest --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm expired tokens return 401 with TOKEN_EXPIRED.
- Open a pull request with the auth middleware changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify token refresh flow works in staging before promoting to production.
Frequently Asked Questions
BugStack tests with expired, valid, and malformed tokens, verifies correct status codes for each case, and confirms no auth-dependent routes are broken before marking it safe.
Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.
Yes. Use short-lived access tokens (15-30 minutes) paired with long-lived refresh tokens stored securely. This limits the window of exposure if an access token is compromised.
clockTolerance allows a small number of seconds of clock skew between the issuing and verifying servers. Set it to 30-60 seconds in distributed systems where server clocks may drift slightly.