How to implement IP whitelisting in NodeJs

How to implement IP whitelisting in NodeJs

To implement IP whitelisting in a Node.js backend, you can use the express-ip-filter package. Here's how you can use it:

  1. Install the express-ip-filter package using npm:
npm install express-ip-filter
  1. Require the express-ip-filter package in your Node.js code:
javascriptCopy codeconst ipfilter = require('express-ip-filter').IpFilter;
  1. Create a middleware function that uses the ipfilter() function to whitelist IP addresses:
const whitelist = ['192.168.0.1', '192.168.0.2']; // Replace with your own list of IP addresses

const ipWhitelist = ipfilter(whitelist, { mode: 'allow' });
app.use(ipWhitelist);
  1. Add the middleware function to your Express app's middleware stack before your other routes:
const express = require('express');
const app = express();

app.use(ipWhitelist);

The ipfilter() function takes two arguments:

  • An array of IP addresses to whitelist

  • An options object that specifies the mode to use (allow or deny), among other things.

In the example above, we're using the allow mode to whitelist the IP addresses specified in the whitelist array.

Note that this implementation only allows access from the specified IP addresses, so be sure to include your own IP address in the whitelist to avoid locking yourself out of your own backend.

Also, IP addresses can be easily spoofed, so this method should not be considered foolproof.