Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Node.js JWT Authentication
Node.js Intermediate FREE

JWT Authentication

Lesson 1 of 17 Intermediate Interactive

JSON Web Tokens (JWT) provide a stateless authentication mechanism.

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));