Generate JWT Tokens in JavaScript
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: JavaScript
What: Generate secure JWT tokens in JavaScript using the jsonwebtoken library for Node.js. Perfect for Express.js APIs, authentication middleware, and stateless session management.
Try it: Use our interactive Jwt-tokens generator or integrate this code into your JavaScript application.
Generate secure JWT tokens in JavaScript using the jsonwebtoken library for Node.js. Perfect for Express.js APIs, authentication middleware, and stateless session management. Looking for other languages? Check our code examples in PHP , Python , Java , C# , C++ , Ruby and Go or use our interactive web generator.
JavaScript Code Example
const jwt = require('jsonwebtoken');
// Secret key (store in environment variables)
const SECRET_KEY = process.env.JWT_SECRET || 'your-256-bit-secret-key';
const ISSUER = 'https://yourdomain.com';
const AUDIENCE = 'https://yourdomain.com';
// Create token payload
const payload = {
user_id: 123,
username: 'john_doe',
role: 'admin'
};
// Generate JWT with options
const token = jwt.sign(payload, SECRET_KEY, {
algorithm: 'HS256',
expiresIn: '1h', // 1 hour
issuer: ISSUER,
audience: AUDIENCE
});
console.log(token);
// Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE2ODAwMDAwMDAsImV4cCI6MTY4MDAwMzYwMCwiaXNzIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20ifQ.signature"
// Verify and decode JWT
try {
const decoded = jwt.verify(token, SECRET_KEY, {
issuer: ISSUER,
audience: AUDIENCE
});
console.log(decoded);
} catch (err) {
console.error('Invalid token:', err.message);
}
// Express.js middleware example
const authenticateJWT = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1]; // Bearer token
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
[EXPLANATION]
The jsonwebtoken library is the most popular JWT implementation for Node.js. It supports both symmetric (HS256) and asymmetric (RS256, ES256) algorithms. The sign() method creates tokens, while verify() validates them. Use environment variables for secret keys and implement proper error handling for token validation.
Expected Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE2ODAwMDAwMDAsImV4cCI6MTY4MDAwMzYwMCwiaXNzIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20ifQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
Common Use Cases
- Express.js/Koa.js API authentication
- Next.js API routes authorization
- GraphQL resolver authentication
- WebSocket authentication
- Serverless function auth (AWS Lambda, Vercel)
Important Notes
-
Install:
npm install jsonwebtoken -
Use
expiresInfor automatic expiration handling - Validate issuer and audience to prevent token misuse
- Use refresh tokens for long-lived sessions
-
Consider
express-jwtmiddleware for Express.js apps
Try Our Interactive Generator
Don't want to write code? Use our free web-based Jwt-tokens generator with instant results.
TRY JWT-TOKENS GENERATOR →Other Programming Languages
View Jwt-tokens generation code examples in PHP
View Jwt-tokens generation code examples in Python
View Jwt-tokens generation code examples in Java
View Jwt-tokens generation code examples in C#
View Jwt-tokens generation code examples in C++
View Jwt-tokens generation code examples in Ruby
View Jwt-tokens generation code examples in Go