Node.js JWT Authentication Error— Fixed [Complete Guide 2026]
⚡ Quick Reference — Handle All JWT Errors
const jwt = require('jsonwebtoken')
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
} catch (err) {
if (err.name === 'TokenExpiredError') // token expired
if (err.name === 'JsonWebTokenError') // invalid signature or malformed
if (err.name === 'NotBeforeError') // token not yet valid
}All JWT Error Types Explained
| Error name | Cause | Fix |
|---|---|---|
| JsonWebTokenError: invalid signature | Sign and verify secrets differ | Jump → |
| TokenExpiredError: jwt expired | Token exp claim has passed | Jump → |
| JsonWebTokenError: jwt malformed | Not a valid JWT string | Jump → |
| JsonWebTokenError: invalid algorithm | alg in token header ≠ expected | Jump → |
| NotBeforeError: jwt not active | nbf claim is in the future | Check server time sync |
Fix: invalid signature
Signing secret differs from verifying secretInvalid signature means the secret used to verify the token is different from the one used when the token was signed. This is almost always caused by a different or missing JWT_SECRET environment variable.
const jwt = require('jsonwebtoken')
// SIGN — uses JWT_SECRET
const token = jwt.sign(
{ userId: user._id, email: user.email },
process.env.JWT_SECRET, // ← secret used to sign
{ expiresIn: '1h' }
)
// VERIFY — must use the EXACT same secret
const decoded = jwt.verify(token, process.env.JWT_SECRET) // ← must match
// Common mistakes that cause invalid signature:
// 1. Different values of JWT_SECRET on different servers
// 2. JWT_SECRET changed after tokens were issued
// 3. Using jwt.decode() instead of jwt.verify() (decode does NOT verify!)
// 4. Whitespace difference: 'secret ' vs 'secret'jwt.decode() does not verify the signature — it just reads the payload. Always use jwt.verify() to validate tokens. jwt.decode() is only for reading already-trusted tokens.
Fix: TokenExpiredError
Token exp claim has passedconst jwt = require('jsonwebtoken')
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1]
if (!token) return res.status(401).json({ error: 'No token provided' })
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
req.user = decoded
next()
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({
error: 'Token expired',
code: 'TOKEN_EXPIRED', // frontend checks this to trigger refresh
})
}
if (err.name === 'JsonWebTokenError') {
return res.status(401).json({ error: 'Invalid token' })
}
next(err)
}
}Set appropriate expiry when signing
// Access token — short lived
const accessToken = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: '15m', // 15 minutes
})
// Refresh token — longer lived
const refreshToken = jwt.sign(payload, process.env.JWT_REFRESH_SECRET, {
expiresIn: '7d', // 7 days
})Fix: jwt malformed
Not a valid JWT stringMalformed JWT means the string passed to jwt.verify() is not a valid JWT. A valid JWT has exactly three parts separated by dots: header.payload.signature.
// Common sources of malformed JWT:
// 1. "Bearer" prefix not stripped
const header = req.headers.authorization // "Bearer eyJhbGci..."
const token = header // ❌ includes "Bearer"
const token = header.split(' ')[1] // ✅ just the JWT
// 2. Double encoding
const token = JSON.stringify(rawToken) // ❌ JSON-stringified
const token = rawToken // ✅ raw string
// 3. Whitespace in the token
const token = req.body.token.trim() // ✅ strip whitespace
// Debug — check what you're verifying
console.log('Token parts:', token.split('.').length) // should be 3JWT Secret from Environment Variable
Missing or wrong JWT_SECRET in production# Generate a strong secret
JWT_SECRET=your-super-long-random-secret-minimum-32-chars
JWT_REFRESH_SECRET=different-secret-for-refresh-tokens
# Generate one in terminal:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"// Check secrets exist before starting
if (!process.env.JWT_SECRET) {
console.error('FATAL: JWT_SECRET not set')
process.exit(1)
}
if (process.env.JWT_SECRET.length < 32) {
console.error('FATAL: JWT_SECRET too short — minimum 32 characters')
process.exit(1)
}Never use a short or obvious secret like 'secret', 'password', or 'jwt'. A weak secret can be brute-forced. Use a cryptographically random string of at least 32 characters.
Complete JWT Auth Middleware
Production-ready Express middlewareconst jwt = require('jsonwebtoken')
// Authenticate — required for protected routes
const authenticate = (req, res, next) => {
// Extract token from Authorization header
const authHeader = req.headers.authorization
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authorization header required' })
}
const token = authHeader.split(' ')[1]
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
req.user = decoded // { userId, email, role, iat, exp }
next()
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' })
}
return res.status(401).json({ error: 'Invalid token' })
}
}
// Authorize — check user role
const authorize = (...roles) => (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' })
}
next()
}
module.exports = { authenticate, authorize }const { authenticate, authorize } = require('../middleware/authenticate')
// Protected route — any authenticated user
router.get('/profile', authenticate, (req, res) => {
res.json({ user: req.user })
})
// Admin only
router.delete('/:id', authenticate, authorize('admin'), async (req, res) => {
await User.findByIdAndDelete(req.params.id)
res.json({ deleted: true })
})Handle JWT in Frontend Correctly
Sending tokens — Axios and fetch patternsimport axios from 'axios'
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
})
// Add token to every request automatically
api.interceptors.request.use((config) => {
const token = localStorage.getItem('accessToken')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
// Handle 401 responses — refresh token or redirect to login
api.interceptors.response.use(
response => response,
async (error) => {
const originalRequest = error.config
if (error.response?.status === 401 &&
error.response?.data?.code === 'TOKEN_EXPIRED' &&
!originalRequest._retry) {
originalRequest._retry = true
try {
const refreshToken = localStorage.getItem('refreshToken')
const { data } = await axios.post('/api/auth/refresh', { refreshToken })
localStorage.setItem('accessToken', data.accessToken)
originalRequest.headers.Authorization = `Bearer ${data.accessToken}`
return api(originalRequest)
} catch {
// Refresh failed — redirect to login
localStorage.clear()
window.location.href = '/login'
}
}
return Promise.reject(error)
}
)
export default apiRefresh Tokens Pattern
Keep users logged in without re-entering credentialsconst jwt = require('jsonwebtoken')
const crypto = require('crypto')
// In-memory refresh token store (use Redis in production)
const refreshTokens = new Set()
// Login — issue both tokens
router.post('/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email })
if (!user || !await user.comparePassword(req.body.password)) {
return res.status(401).json({ error: 'Invalid credentials' })
}
const accessToken = jwt.sign(
{ userId: user._id, email: user.email, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
)
const refreshToken = crypto.randomBytes(64).toString('hex')
refreshTokens.add(refreshToken)
res.json({ accessToken, refreshToken })
})
// Refresh — issue new access token
router.post('/refresh', (req, res) => {
const { refreshToken } = req.body
if (!refreshToken || !refreshTokens.has(refreshToken)) {
return res.status(401).json({ error: 'Invalid refresh token' })
}
// Decode the old access token payload (without verification)
// In production: look up user from database using stored refresh token
const newAccessToken = jwt.sign(
{ userId: 'user._id', email: 'user.email' },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
)
res.json({ accessToken: newAccessToken })
})
// Logout — invalidate refresh token
router.post('/logout', (req, res) => {
refreshTokens.delete(req.body.refreshToken)
res.json({ message: 'Logged out' })
})In production, store refresh tokens in Redis or your database — not in memory. In-memory storage loses all tokens on server restart.
Complete JWT Authentication Flow
- 1
User sends email + password
POST /api/auth/login
- 2
Server verifies credentials
bcrypt.compare(password, hash)
- 3
Server creates JWT access token (15m)
jwt.sign(payload, JWT_SECRET, { expiresIn: '15m' })
- 4
Server creates refresh token (7d)
crypto.randomBytes() — stored in DB/Redis
- 5
Client stores tokens
httpOnly cookie (secure) or localStorage
- 6
Client sends token with each request
Authorization: Bearer <accessToken>
- 7
Server verifies token on protected routes
jwt.verify(token, JWT_SECRET)
- 8
On 401 TOKEN_EXPIRED — client refreshes
POST /api/auth/refresh with refreshToken
How to Prevent JWT Errors
- Store JWT_SECRET in .env — never hardcode it in source code
- Use a minimum 32-character random secret: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
- Always use jwt.verify() — never jwt.decode() for security checks
- Handle TokenExpiredError specifically — return TOKEN_EXPIRED code for frontend to trigger refresh
- Validate JWT_SECRET exists at startup and exit if missing
- Use short access token expiry (15m) paired with longer refresh tokens (7d)
- Store refresh tokens in Redis/database — never in memory alone
Frequently Asked Questions
What causes JWT invalid signature error?+−
How do I fix JWT token expired error?+−
JWT works locally but invalid signature in production?+−
How do I extract JWT from Authorization header?+−
Should I store JWT in localStorage or a cookie?+−
How long should JWT tokens expire?+−
Need Expert Help?
We Build Secure Node.js Authentication Systems
Softplix builds full-stack applications with secure authentication. Need help with JWT, OAuth, or a complete auth system? We can help.
Talk to an Engineer