JSON Web Tokens (JWT) provide a stateless authentication mechanism.
Getting Started
What is Node.js?
Modules & NPM
Modules & NPM
Process & Environment
Process & Environment Variables
Caching & Performance
Redis Caching
GraphQL with Node.js
GraphQL Basics
Node.js
Intermediate
FREE
JWT Authentication
Lesson 1 of 17
Intermediate
Interactive
Syntax
NODEJS
const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: 1 }, 'secret', { expiresIn: '7d' }); const decoded = jwt.verify(token, 'secret');
JWT Authentication
NODE
const jwt = require("jsonwebtoken"); const SECRET = "your-secret-key"; // Generate token function generateToken(user) { return jwt.sign( { id: user.id, email: user.email }, SECRET, { expiresIn: "24h" } ); } // Verify middleware function auth(req, res, next) { const token = req.headers.authorization?.split(" ")[1]; if (!token) return res.status(401).json({ error: "No token" }); try { const decoded = jwt.verify(token, SECRET); req.user = decoded; next(); } catch { res.status(401).json({ error: "Invalid token" }); } } // Demo const token = generateToken({ id: 1, email: "alice@example.com" }); console.log("Token:", token); console.log("Decoded:", jwt.verify(token, SECRET));