Block user based on IP address in Express or any other Node HTTP server

This is an easy task, but you will need to find a way to get the user’s IP address. And here’s how.

First, let’s assume we have a simple Express server:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  ...
});

app.listen(port, () => console.log(`App listening on port ${port}!`))

Now we only need to get the IP address and end the response in case it’s a match. The IP address could be the one provided by the proxy via X-FORWARDER-FOR header, or the one that is provided in request’s socket object.

app.get('/', (req, res) => {
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    const ipv = req.socket.remoteFamily;
    console.log(ipv, ip);
    if (ip == '127.0.0.1' || ip === '::1') { // exit if it's a particular ip
        res.writeHead(403);
        return res.end('Error 403: Your IP is blocked');
    }
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('It works!');
});

That should give you an idea. Additionally, you can get the IP version from req.socket.remoteFamily. Open localhost:3000 in your browser and see if you get Error 403: Your IP is blocked. You should also see IPv6 ::1 in your terminal which is the result of console.log(ipv, ip);


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

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