avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Get Real Client IP In FeathersJS

Tue Feb 25 2020

IP Address In Request Headers Are Usually Set by Nginx

Your Nginx reverse proxy config should be something like this:

server {
    listen 80;
    server_name example.com;
    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # add multiple forwarded ip address
        proxy_set_header X-Real-IP $remote_addr; # add single remote ip address, recommemded
        proxy_pass http://127.0.0.1:3000/;
        // other configs ...
    }
}

In FeathersJS

By default, you are able to touch request headers in feathers context context.params.headers, it is managed by FeathersJS, and no matter what transport method you are using, http or socket-io, you will be able to get it.

What does It Look like In Context

We can log the context.params.headers in a hook to find out:

module.exports = {
  before: {
    all: [log(), (context) => {
      console.log("headers from hook", context.params.headers);
      return context;
    }],
  },
}

You will see data like below:

const headers = 
{
  "x-forwarded-host": "x-forwarded-host", // given by nginx
  "x-forwarded-server": "x-forwarded-server", // given by nginx
  "x-forwarded-for": "REAL_IP", // given by nginx
  "x-real-ip": "REAL_IP", // given by nginx
  "host": "LOCALHOST:3030",
  "accept": "*/*",
  "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
  "origin": "http://example.com",
  "sec-fetch-site": "cross-site",
  "sec-fetch-mode": "cors",
  "sec-fetch-dest": "empty",
  "referer": "http://example.com",
  "accept-encoding": "gzip, deflate, br",
  "accept-language": "zh-CN,zh;q=0.9"
}

The x-real-ip will provide a single remote IP address set by Nginx.