How to implement JWT in Node.js

JSON Web Tokens provide a secure and stateless authentication mechanism for Node.js applications, eliminating server-side session storage. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve implemented JWT authentication in countless production APIs and enterprise applications. The most reliable approach uses the jsonwebtoken package to sign tokens with user data and verify them on protected routes. This method provides excellent scalability and security for modern web applications and APIs.

Use the jsonwebtoken package to sign and verify JWT tokens for secure authentication.

const jwt = require('jsonwebtoken')

// Generate JWT token
function generateToken(user) {
  return jwt.sign(
    { id: user.id, email: user.email },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  )
}

// Verify JWT token middleware
function verifyToken(req, res, next) {
  const token = req.headers['authorization']?.split(' ')[1]

  if (!token) {
    return res.status(401).json({ error: 'Access denied' })
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) return res.status(403).json({ error: 'Invalid token' })
    req.user = decoded
    next()
  })
}

This code creates a token generator that signs user data with a secret key and sets an expiration time. The verification middleware extracts the token from the Authorization header, validates it, and attaches the decoded user data to the request object. This enables stateless authentication where the server doesn’t need to store session data.

Best Practice Note:

This is the exact JWT implementation we use in CoreUI backend services for secure API authentication. Always use strong secret keys stored in environment variables and implement token refresh mechanisms for enhanced security.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team