How to do whitelist of IP's in Express?

express, javascript, node.js

Solution

You can simply add your own middleware that checks the IPs, no need to include another module.

You can see the ip from the request with `req.connection.remoteAddress`.

Before you define your routes, add something like this:

// Custom Middleware
app.use((req, res, next) => {
let validIps = ['::12', '127.0.0.1']; // Put your IP whitelist in this array

  if(validIps.includes(req.connection.remoteAddress)){
      // IP is ok, so go on
      console.log("IP ok");
      next();
  }
  else{
      // Invalid ip
      console.log("Bad IP: " + req.connection.remoteAddress);
      const err = new Error("Bad IP: " + req.connection.remoteAddress);
      next(err);
  }
})

This will throw an error if an invalid ip comes in. Below all your routes, add something like this:

// Error handler
app.use((err, req, res, next) => {
    console.log('Error handler', err);
    res.status(err.status || 500);
    res.send("Something broke");
});

Problem

I need to block every IP address from accessing my site except one or two IP's provided by myself. I have tried many modules but nothing seems to work. ``` var express = require('express') var AccessControl = require('express-ip-access-control'); var app = express() app.get('/', function (req, res) { res.send('Hello World!') }) var middleware = AccessControl(options); app.use(AccessControl(options)); var options = { mode: 'deny', denys: [], allows: ['**8.1**.1.**'], forceConnectionAddress: false, log: function(clientIp, access) { console.log(clientIp + (access ? ' accessed.' : ' denied.')); }, statusCode: 401, redirectTo: '', message: 'Unauthorized' }; app.listen(3000, function () { console.log(' app listening on port 3000!') }) ``` on running and accessing my site from my above code i am getting the console message as ``` ::ffff:127.0.0.1 accessed. ::ffff:127.0.0.1 accessed. ::ffff:127.0.0.1 accessed. ::ffff:127.0.0.1 accessed. ``` any help?

Original source