JWT Tokens in JavaScript (Node.js): Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

JWT Tokens in JavaScript (Node.js)



JSON Web Token (JWT) is an open standard (RFC 7519) for creating access tokens based on JSON. JWT is widely used for authentication and information exchange between client and server in modern Node.js web applications. In this article, we will cover how to work with JWT in the Node.js environment using the popular jsonwebtoken library.



What is JWT?



JWT consists of three parts separated by dots:



  • Header — contains the token type and signing algorithm (e.g., HS256 or RS256).
  • Payload — contains the data (claims): user ID, role, token expiration time, etc.
  • Signature — created based on the header, payload, and secret key. The signature ensures the token has not been altered.


Visually, a JWT looks like this: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c



Installing the jsonwebtoken Library



To work with JWT in Node.js, use the jsonwebtoken package. Install it via npm:



npm install jsonwebtoken


After installation, you can import the library into your project:



const jwt = require('jsonwebtoken');


Generating (Signing) a JWT Token



To create a token, use the jwt.sign() method. It takes three main parameters:



  • payload — an object with data to be encoded in the token.
  • secretOrPrivateKey — the secret key (or private key for RSA/ECDSA algorithms).
  • options — an object with options, e.g., expiresIn to set the token's lifetime.


Example of generating a token:



const jwt = require('jsonwebtoken');

const payload = { userId: 12345, role: 'user'};

const secretKey = 'your-secret-key-here';

const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });

console.log('Generated JWT:', token);


In this example, the token will be valid for 1 hour. You can also specify time in seconds (expiresIn: 3600) or in other formats, e.g., '7d' (7 days) or '30m' (30 minutes).



Verifying a JWT Token



To verify the token's authenticity, use the jwt.verify() method. It returns the decoded payload if the token is valid, or throws an error if the token has expired or the signature is invalid.



const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIs...'; // your tokenconst secretKey = 'your-secret-key-here';

try { const decoded = jwt.verify(token, secretKey); console.log('Decoded data:', decoded);} catch (err) { console.error('Verification error:', err.message);}


If the token has expired, you will get a 'jwt expired' error. If the signature is invalid — 'invalid signature'.



Decoding Without Signature Verification



Sometimes you just need to read data from the token without verifying the signature (e.g., for debugging). Use jwt.decode() for this:



const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIs...';const decoded = jwt.decode(token);

console.log('Payload without verification:', decoded);


Important: jwt.decode() does not verify the signature, so do not use it for authentication in production.



Middleware for Express with JWT



In Express web applications, JWT is often used to protect routes. Let's create a simple middleware that checks the token from the header <

Recommendations