White Listing IP in NodeJS Express Server
White Listing IP in NodeJS Express Server

Node.JS as you know is single threaded, asynchronous, event-driven architecture, Is so popular JavaScript JavaScript runtime environment for building high performance web application or back-end application like express server or Rest API’s.

You are here to know how can I increase the security level of my NodeJS express server by whitelisting IP to use our node server.

In this NodeJS article let’s explore how to enhance security of our NodeJS Express by adding middleware to check the whitelisted IP and allow only specific Client IP address to access our server.

Video Tutorial


The code complete source code with explanation is as below

Allow Only one specific IP

index.js

const express = require('express')

const app = express();

const checkIpAccess = (req,res,next)=>{
    const ALLOWEDID = "192.168.29.78";
    const CLIENTIP = req.ip;

    
    if(CLIENTIP === ALLOWEDID || CLIENTIP === "::ffff:"+ALLOWEDID){
      next();
    }else{
      res.status(403).send("Forbidden");
    }
    
}

app.use(checkIpAccess);

app.get('/',(req,res)=>{
  res.send(`ALLOWED ACCESS  ${req.ip}`);
})

app.listen(3000,()=>{
  console.log("Server Running at port 3000");
})

Whitelisting multiple IP’s in NodeJS

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

const checkIpAccess = (req, res, next) => {
    const ALLOWEDIPS = ["192.168.29.78", "192.168.29.79", "192.168.29.80"];
    const CLIENTIP = req.ip;

    if (ALLOWEDIPS.includes(CLIENTIP) || ALLOWEDIPS.includes("::ffff:" + CLIENTIP)) {
        next();
    } else {
        res.status(403).send("Forbidden");
    }
}

app.use(checkIpAccess);

app.get('/', (req, res) => {
    res.send(`ALLOWED ACCESS  ${req.ip}`);
})

app.listen(3000, () => {
    console.log("Server Running at port 3000");
})

Understanding the above code

The above code make use of ExpressJS to run a NodeJS server, which makes use of middleware function checkIpAccess thta is responsible to check the client request IP address if that IP exist in our allowed whitelisted IP list then grant the user to use our nodejs server else return a status error 403 that is forbidden.

Benefits of IP Whitelisting

Implementing IP whitelisting in your Node.js Express server offers several security advantages:

  1. Access Control: Only requests originating from the specified IP address are permitted, providing a level of access control.
  2. Reduced Attack Surface: By restricting access to a single IP, you minimize the potential attack surface, making it more challenging for unauthorized users to interact with your server.
  3. Enhanced Security: IP whitelisting is an additional layer of security, complementing other security measures you may have in place.