Node.jsJWTError Fix2026 Updated

Node.js JWT Authentication Error— Fixed [Complete Guide 2026]

January 20267 min readNode.js · Express · All OS

⚡ Quick Reference — Handle All JWT Errors

middleware/auth.js
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 nameCauseFix
JsonWebTokenError: invalid signatureSign and verify secrets differJump →
TokenExpiredError: jwt expiredToken exp claim has passedJump →
JsonWebTokenError: jwt malformedNot a valid JWT stringJump →
JsonWebTokenError: invalid algorithmalg in token header ≠ expectedJump →
NotBeforeError: jwt not activenbf claim is in the futureCheck server time sync
1

Fix: invalid signature

Signing secret differs from verifying secret
2 min

Invalid 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.

server.js
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.

2

Fix: TokenExpiredError

Token exp claim has passed
3 min
middleware/auth.js
const 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

server.js
// 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
})
3

Fix: jwt malformed

Not a valid JWT string
2 min

Malformed 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.

routes/protected.js
// 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 3
4

JWT Secret from Environment Variable

Missing or wrong JWT_SECRET in production
2 min
.env
# 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'))"
server.js — validate at startup
// 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.

5

Complete JWT Auth Middleware

Production-ready Express middleware
5 min
middleware/authenticate.js
const 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 }
routes/users.js
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 })
})
6

Handle JWT in Frontend Correctly

Sending tokens — Axios and fetch patterns
3 min
Frontend — api.js
import 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 api
7

Refresh Tokens Pattern

Keep users logged in without re-entering credentials
5 min
routes/auth.js
const 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. 1

    User sends email + password

    POST /api/auth/login

  2. 2

    Server verifies credentials

    bcrypt.compare(password, hash)

  3. 3

    Server creates JWT access token (15m)

    jwt.sign(payload, JWT_SECRET, { expiresIn: '15m' })

  4. 4

    Server creates refresh token (7d)

    crypto.randomBytes() — stored in DB/Redis

  5. 5

    Client stores tokens

    httpOnly cookie (secure) or localStorage

  6. 6

    Client sends token with each request

    Authorization: Bearer <accessToken>

  7. 7

    Server verifies token on protected routes

    jwt.verify(token, JWT_SECRET)

  8. 8

    On 401 TOKEN_EXPIRED — client refreshes

    POST /api/auth/refresh with refreshToken

How to Prevent JWT Errors

Frequently Asked Questions

What causes JWT invalid signature error?+
The secret used to verify the token is different from the one used to sign it. Check that process.env.JWT_SECRET is the same value when signing and verifying. On different servers, the secret must be identical.
How do I fix JWT token expired error?+
The token's exp claim has passed. Either issue a new token (login again) or implement refresh tokens. In your middleware, catch TokenExpiredError specifically and return a 401 with a 'token expired' message so the frontend knows to refresh.
JWT works locally but invalid signature in production?+
Your JWT_SECRET environment variable is either not set in production or has a different value. Check that the secret is set via your platform dashboard (Heroku, Railway etc.) and matches exactly — including any trailing spaces or newlines.
How do I extract JWT from Authorization header?+
The standard pattern: const authHeader = req.headers.authorization; if (!authHeader?.startsWith('Bearer ')) return res.status(401).json({ error: 'No token' }); const token = authHeader.split(' ')[1];
Should I store JWT in localStorage or a cookie?+
Cookies with httpOnly: true, secure: true, sameSite: 'strict' are more secure — JavaScript cannot access them so XSS attacks cannot steal the token. localStorage is simpler but vulnerable to XSS. For most apps, httpOnly cookies are recommended.
How long should JWT tokens expire?+
Access tokens: 15 minutes to 1 hour. Refresh tokens: 7 to 30 days. Short access token expiry limits the damage if a token is stolen. Pair with refresh tokens so users stay logged in without re-entering credentials.

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