JsonWebToken for JavaScript (Node.js): Complete Guide with Examples

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

JsonWebToken for JavaScript (Node.js): Complete Guide with Examples

\n\n

What It Is and Why You Need It

\n\n

The 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).

\n\n

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\n

The 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.

\n\n

Installation

\n\n

To install the JsonWebToken library in your Node.js project, run the following command in the terminal:

\n\n
npm install jsonwebtoken
\n\n

If you are using Yarn:

\n\n
yarn add jsonwebtoken
\n\n

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

\n\n
const jwt = require('jsonwebtoken');\n// or for ES modules:\n// import jwt from 'jsonwebtoken';
\n\n

Quick Start — Minimal Working Example

\n\n

Let's create a simple example demonstrating the creation and verification of a JWT token:

\n\n
const 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\n

This example shows three main operations: creating a token using sign(), verifying its authenticity using verify(), and simple decoding without signature verification using decode().

\n\n

Main Methods/Functions/Classes

\n\n

1. jwt.sign(payload, secretOrPrivateKey, [options, callback])

\n

Signature: jwt.sign(payload: Object|Buffer, secretOrPrivateKey: string|Buffer, options?: Object, callback?: Function) => string|void

\n

What it does: Creates (signs) a JW

Recommendations