[ Expressjs ] Cracking nuts, put the IP Address to BlackList

Peter Chang
HackerNoon.com
4 min readDec 28, 2016

--

The best way dealing with the un-welcome people is kicking him out of your party. The best way dealing with un-welcome IPs is to BLACK LIST.

Background about today, an APP service running on Node.js server which included a static HTML website and API service. We got few un-welcome IPs list on hand and my boss told me“Peter, black list them.”.

I love Node.js and Express, the design of middleware speedups I get the job done and leaving office early to have a Friday night.

The problem is being broken down to three parts:

  1. Define blacklist IP
  2. Geting client IP
  3. Blocking Client IP, if it is in the blacklist

Extracting Client ID in Express.js is super easy, Router and req are tools which accelerating to extract all the client information which included Header, Cookies, Post Body, Get URL Parameters etc.

Define blacklist IP

Putting unwelcome IPs in an array, which will be used in middleware to check where the router is going to direct.

Fetch Client IP

Express provide a super friendly req to fetch the client IP within few line of code.

req.connection.remoteAddress return the IP, could be ipv4 or ipv6.

Blocking Client IP, if it is in the blacklist

Add an USER BLOCKING middleware function(req, res, next) inside app.use( ), this middleware function will be executed for every request to the app. Like a filter which let the right IPs to go through.

Putting all together

It is an example of putting above 3 parts together in a Express.js framework. To modify one which fit your BlackList IPs, go and push your IPs in BLACKLIST Array and they will never ever access the service.

#Thanks to Pierre Chamberlain, corrected the mistake BLACKLIST.indexOf(ipAddress) === -1

Remark

  1. req.headers[‘x-forwarded-for’]
  2. req.connection.remoteAddress
  3. req.connection.socket.remoteAddress

1) x-forwarded-for: client, proxy1, proxy2, proxy3
If you are running behind a proxy like NGiNX or what have you, only then you should check for ‘x-forwarded-for’ (by alessioalex)

2) req.connection.remoteAddress
Default server is listening to IPv6 connections and the IPV6_V6ONLY flag isn’t set with the result that IPv4 connections are processed by the same socket. (by Wladimir Palant)

3) req.connection.socket.remoteAddress
On https, req.connection.remoteAddress is undefined, but req.connection.socket.remoteAddress does work(by Mathijs Kwik)

You may also like:

[Javascript] override Object.constructor( )
[Expressjs] override res.send

Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.

--

--