Home โ†’ Block user based on IP address in Express or any other Node HTTP server

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

By ยท Node.js & JavaScript developer
Published March 11, 2023

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

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.