Handling JWT Token Removal on Logout in Node.js with Express

Handling JWT Token Removal on Logout in Node.js with Express

JSON Web Tokens (JWT) are widely used for authentication in web applications. When a user logs out, it’s essential to invalidate or remove their JWT token to enhance security. In this guide, we’ll walk through the process of handling token removal on logout using Node.js and Express.

Client-Side Implementation

Clear Tokens from Local Storage

When a user clicks on the logout button, remove the JWT token from the client-side storage. Here’s an example using JavaScript:


// logout.js

// Function to clear JWT token from local storage
function logout() {
    localStorage.removeItem('jwtToken');
    // Redirect or update UI as needed
}

Invoke Logout Function

In your HTML file or client-side script, call the logout function when the logout button is clicked.


<!-- index.html -->

<button onclick="logout()">Logout</button>

<script src="logout.js"></script>

Server-Side Implementation

Install Required Packages

Make sure you have Node.js installed. Initialize your project and install necessary packages:

npm init -y
npm install express jsonwebtoken

Create an Express Server

Set up a basic Express server. For simplicity, we’ll create a single route for token validation.


// server.js

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

const app = express();
const PORT = 3000;

// Dummy secret key (replace with a secure key in a real-world scenario)
const secretKey = 'your-secret-key';

// Middleware to validate JWT tokens
function validateToken(req, res, next) {
    // Extract the token from the request headers or cookies
    const token = req.headers.authorization;

    if (!token) {
        return res.status(401).json({ error: 'Unauthorized' });
    }

    // Verify the token
    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) {
            return res.status(401).json({ error: 'Invalid token' });
        }

        // Token is valid; proceed to the next middleware or route
        next();
    });
}

// Example protected route
app.get('/protected', validateToken, (req, res) => {
    res.json({ message: 'This is a protected route' });
});

app.listen(PORT, () => {
    console.log(`Server is running on <http://localhost>:${PORT}`);
});

Handle Token Removal on Logout

Implement a route on the server that handles token removal on logout. When a user logs out, add the token to a blacklist or perform any other necessary actions.

// server.js (continued)

const blacklist = new Set();

// Route to handle token removal on logout
app.post('/logout', (req, res) => {
    const token = req.headers.authorization;

    if (!token) {
        return res.status(400).json({ error: 'Token not provided' });
    }

    // Add the token to the blacklist
    blacklist.add(token);

    res.json({ message: 'Logout successful' });
});

// Updated token validation middleware
function validateToken(req, res, next) {
    const token = req.headers.authorization;

    if (!token || blacklist.has(token)) {
        return res.status(401).json({ error: 'Unauthorized' });
    }

    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) {
            return res.status(401).json({ error: 'Invalid token' });
        }

        next();
    });
});

Test the Implementation

Use a tool like Postman or curl to test the protected route and the logout functionality. Make requests to the /protected route with a valid token and try the /logout route to simulate a logout.


# Example request to /protected
curl -X GET <http://localhost:3000/protected> -H "Authorization: YOUR_VALID_JWT_TOKEN"

# Example request to /logout
curl -X POST <http://localhost:3000/logout> -H "Authorization: YOUR_VALID_JWT_TOKEN"

In real project, you can put blacklist token into database or some memory to caching this before they are expired.

This guide provides a basic example of handling JWT token removal on logout in a Node.js and Express environment. Depending on your specific requirements and the authentication library you’re using, you may need to adapt and extend these concepts. Always ensure that you handle tokens securely and consider best practices for authentication and authorization in your application.

Leave a Reply

Your email address will not be published. Required fields are marked *