JWT Tokens in JavaScript (Node.js): Complete Guide to the jsonwebtoken Library
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 the Node.js ecosystem, the most popular library for working with JWT is jsonwebtoken. In this article, we will thoroughly cover how to install, configure, and use this library to build secure web applications.
What is JWT and Why is it Needed?
JWT is a string consisting of three parts separated by dots: Header, Payload, and Signature. The token looks like this: xxxxx.yyyyy.zzzzz. The main advantages of JWT:
- Security — the token is signed with a secret key or a key pair (RSA/ECDSA), guaranteeing its integrity.
- Self-contained — all necessary information for verification is contained within the token itself, reducing the number of database queries.
- Cross-platform — JWT works with any programming language and platform.
- Flexibility — you can add any custom data to the payload (e.g., user ID, role).
Installing the jsonwebtoken Library
To work with JWT in Node.js, install the jsonwebtoken package via npm:
npm install jsonwebtokenAfter installation, include the library in your file:
const jwt = require('jsonwebtoken');Generating (Signing) a JWT Token
To create a token, use the jwt.sign(payload, secretOrPrivateKey, options) method. Let's look at a basic example:
const jwt = require('jsonwebtoken');
const payload = { userId: 123, role: 'user'};
const secretKey = 'my_super_secret_key_123';
const token = jwt.sign(payload, secretKey, { expiresIn: '1h', // token expires in 1 hour algorithm: 'HS256' // signing algorithm (default is HS256)});
console.log('Generated token:', token);Important: Never store the secret key in code. Use environment variables (.env file). To do this, install the dotenv package:
npm install dotenvExample usage with environment variables:
require('dotenv').config();const jwt = require('jsonwebtoken');
const token = jwt.sign( { userId: 456 }, process.env.JWT_SECRET, { expiresIn: '7d' });Verifying a JWT Token
To verify the authenticity of a token, use the jwt.verify(token, secretOrPublicKey, options) method. It returns the payload if the token is valid, or throws an error if the token is expired or invalid.
const token = 'your_token_here';
try { const decoded = jwt.verify(token, process.env.JWT_SECRET); console.log('Decoded data:', decoded); // { userId: 456, iat: 1700000000, exp: 1700600000 }} catch (err) { if (err.name === 'TokenExpiredError') { console.log('Token expired'); } else if (err.name === 'JsonWebTokenError') { console.log('Invalid token'); } else { console.log('Verification error:', err.message); }}Note the iat (issued at) and exp (expiration time) fields, which are automatically added if the expiresIn parameter is specified.
Middleware for Express.js
In real applications, JWT is typically verified in middleware. Here is an example for Express.js:
const express = require('express');const jwt = require('jsonwebtoken');require('dotenv').c