← Back to all snippets
JAVASCRIPT

Securely Validate JWT Tokens in Node.js Express API

Implement secure server-side validation of JWT tokens to authenticate and authorize users in your Node.js API, ensuring data integrity and user access control.

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

app.use(express.json()); // For parsing application/json

// Secret key for signing and verifying tokens
const JWT_SECRET = process.env.JWT_SECRET || 'your_very_secure_secret_key_change_me';
// For production, store JWT_SECRET securely as an environment variable

// Middleware to verify JWT token
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Expected format: "Bearer TOKEN"

    if (token == null) {
        return res.status(401).json({ message: 'Authentication token required.' }); // No token provided
    }

    jwt.verify(token, JWT_SECRET, (err, user) => {
        if (err) {
            if (err.name === 'TokenExpiredError') {
                return res.status(403).json({ message: 'Authentication token expired.' });
            }
            return res.status(403).json({ message: 'Invalid authentication token.' }); // Token is invalid (e.g., wrong signature)
        }
        req.user = user; // Attach user payload to request object
        next(); // Proceed to the next middleware/route handler
    });
};

// Example protected route
app.get('/protected', authenticateToken, (req, res) => {
    res.json({
        message: 'You accessed a protected route!',
        user: req.user
    });
});

// Example login route (generates a token)
app.post('/login', (req, res) => {
    // In a real app, validate username/password against a database
    const { username, password } = req.body;
    if (username === 'testuser' && password === 'testpass') {
        const user = { id: 1, username: username, role: 'admin' };
        const accessToken = jwt.sign(user, JWT_SECRET, { expiresIn: '1h' }); // Token expires in 1 hour
        return res.json({ accessToken: accessToken });
    }
    res.status(401).json({ message: 'Invalid credentials.' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates how to securely validate JSON Web Tokens (JWT) for authentication and authorization in an Express.js API. It includes an `authenticateToken` middleware that extracts a bearer token from the request header, verifies its signature and expiration using a secret key, and attaches the decoded user payload to the request object. This ensures only authenticated and authorized users can access protected routes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs