JsonWebToken for JavaScript (Node.js): Complete Guide with Examples
\n\nWhat It Is and Why You Need It
\n\nThe JsonWebToken library (often used as jsonwebtoken or jwt) is one of the most popular libraries for working with JSON Web Tokens (JWT) in the Node.js environment. JWT is a compact and self-contained way to transmit information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret key (HMAC algorithm) or a public/private key pair (RSA or ECDSA algorithms).
The main purpose of the library is to implement authorization and authentication mechanisms in web applications and APIs. When a user successfully logs in, the server creates a JWT and sends it to the client. The client then sends this token with each subsequent request, allowing the server to verify the user's identity without needing to store session data on the server. This makes JWT an ideal solution for building RESTful APIs, microservice architectures, and single-page applications (SPAs).
\n\nThe jsonwebtoken library provides a complete set of tools for creating (sign), verifying (verify), and decoding (decode) tokens. It supports all standard signing algorithms, including HS256, RS256, ES256, and allows flexible configuration of token expiration time, adding custom fields (claims), and working with public/private keys. Thanks to its reliability and simplicity, this library is used in thousands of projects worldwide and is the de facto standard for working with JWT in the Node.js ecosystem.
Installation
\n\nTo install the JsonWebToken library in your Node.js project, run the following command in the terminal:
\n\nnpm install jsonwebtoken\n\nIf you are using Yarn:
\n\nyarn add jsonwebtoken\n\nAfter installation, you can import the library into your code:
\n\nconst jwt = require('jsonwebtoken');\n// or for ES modules:\n// import jwt from 'jsonwebtoken';\n\nQuick Start — Minimal Working Example
\n\nLet's create a simple example demonstrating the creation and verification of a JWT token:
\n\nconst jwt = require('jsonwebtoken');\n\n// Secret key (in a real project, store it in .env)\nconst secretKey = 'my-super-secret-key-123';\n\n// Data we want to encode in the token (payload)\nconst payload = {\n userId: 12345,\n username: 'john_doe',\n role: 'user'\n};\n\n// 1. CREATING A TOKEN\nconst token = jwt.sign(payload, secretKey, { expiresIn: '1h' });\nconsole.log('Created token:', token);\n\n// 2. VERIFYING THE TOKEN\ntry {\n const decoded = jwt.verify(token, secretKey);\n console.log('Decoded data:', decoded);\n // Output: { userId: 12345, username: 'john_doe', role: 'user', iat: ..., exp: ... }\n} catch (err) {\n console.error('Token verification error:', err.message);\n}\n\n// 3. DECODING WITHOUT SIGNATURE VERIFICATION (NOT RECOMMENDED for authorization!)\nconst decodedWithoutVerify = jwt.decode(token);\nconsole.log('Decoded without verification:', decodedWithoutVerify);\n\nThis example shows three main operations: creating a token using sign(), verifying its authenticity using verify(), and simple decoding without signature verification using decode().
Main Methods/Functions/Classes
\n\n1. jwt.sign(payload, secretOrPrivateKey, [options, callback])
\nSignature: jwt.sign(payload: Object|Buffer, secretOrPrivateKey: string|Buffer, options?: Object, callback?: Function) => string|void
What it does: Creates (signs) a JW
Also in library
JWT Tokens in Go (Golang): golang-jwt Library and Usage Examples
Data Validation in C++: Libraries and Methods (libvalidate, nlohmann/json, Boost)
Hyper for Rust: Complete Guide with Examples
Working with XML in Go (Golang): The encoding/xml Standard Library
NodaTime C# (.NET) Guide: Complete Tutorial with Examples