How to Validate JSON Web Tokens (JWT) in Node.js

JSON Web Tokens (JWT) are widely used for authentication and authorization in Node.js applications. Validation ensures the token hasn’t been tampered with, is not expired, and was issued by a trusted source. This tutorial walks you through the essential steps to validate JWTs using the popular `jsonwebtoken` library.

Before proceeding, make sure you have Node.js installed and a project initialized. You’ll also need the secret key (or public key for RS256) that was used to sign the token. If you don’t have a token, you can create one for testing using jwt.sign().

Article illustration

1. Install the Required Package

Add the `jsonwebtoken` library to your project:

npm install jsonwebtoken

This module provides `jwt.verify()` which handles signature verification and expiration checking in one call.

2. Basic Token Validation

Import the library and call `jwt.verify()` with the token and your secret key:

const jwt = require('jsonwebtoken');

const token = "your.jwt.token.here";
const secret = "your-secret-key";

try {
  const decoded = jwt.verify(token, secret);
  console.log('Valid token:', decoded);
} catch (err) {
  console.error('Invalid token:', err.message);
}

The `decoded` object contains the payload (e.g., `userId`, `role`) plus `iat` and `exp` fields if present.

3. Handle Common Validation Errors

`jwt.verify()` throws specific errors you should catch:

  • TokenExpiredError – the token’s expiration time has passed.
  • JsonWebTokenError – signature mismatch, malformed token, or other issues.
  • NotBeforeError – the `nbf` claim hasn’t been reached yet.

Always wrap the call in a try/catch block to deliver appropriate client responses (e.g., 401 Unauthorized).

4. Using Async/Await with Promises

For cleaner code, wrap `jwt.verify()` in a Promise:

function verifyToken(token) {
  return new Promise((resolve, reject) => {
    jwt.verify(token, secret, (err, decoded) => {
      if (err) reject(err);
      else resolve(decoded);
    });
  });
}

// Usage
(async () => {
  try {
    const decoded = await verifyToken(token);
    console.log('Token is valid');
  } catch (err) {
    console.error('Validation failed');
  }
})();

Conclusion

Validating JWTs in Node.js is straightforward with the `jsonwebtoken` library. Always check for errors, handle expiration gracefully, and never trust a token without verification. For production, store secrets in environment variables and consider rotating keys regularly.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *