SyntaxStudy
Sign Up
Node.js Beginner 12 min read

JWT Authentication

JSON Web Tokens (JWT) are a compact, self-contained way to transmit authentication information between parties. A JWT contains a header, payload, and signature. The server signs the token; clients send it in the Authorization header on subsequent requests.

Example
// npm install jsonwebtoken bcrypt
const jwt     = require('jsonwebtoken');
const bcrypt  = require('bcrypt');
const express = require('express');
const app     = express();
app.use(express.json());

const JWT_SECRET  = process.env.JWT_SECRET || 'change-me-in-production';
const JWT_EXPIRES = '7d';

// Fake user store:
const users = [
    { id: 1, username: 'alice', password: '$2b$12$hashedPasswordHere' },
];

// Login — issue a token:
app.post('/auth/login', async (req, res) => {
    const { username, password } = req.body;
    const user = users.find(u => u.username === username);
    if (!user) return res.status(401).json({ error: 'Invalid credentials' });

    const valid = await bcrypt.compare(password, user.password);
    if (!valid) return res.status(401).json({ error: 'Invalid credentials' });

    const token = jwt.sign(
        { userId: user.id, username: user.username },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES }
    );
    res.json({ token });
});

// Auth middleware — protect routes:
function authenticate(req, res, next) {
    const header = req.headers.authorization;
    if (!header || !header.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'No token provided' });
    }
    try {
        const token = header.split(' ')[1];
        req.user = jwt.verify(token, JWT_SECRET);
        next();
    } catch {
        res.status(401).json({ error: 'Invalid or expired token' });
    }
}

// Protected route:
app.get('/api/profile', authenticate, (req, res) => {
    res.json({ user: req.user });
});

app.listen(3000);