'what is the difference between request.ip and request.raw.ip in fastify?

Difference between request.ip and request.raw.ip in fastify.

Request The first parameter of the handler function is Request. Request is a core Fastify object containing the following fields:

raw - the incoming HTTP request from Node core ip - the IP address of the incoming request

It contains more fields I am just showing relevant fields to my question. you can check more field out here -> https://www.fastify.io/docs/latest/Request/



Solution 1:[1]

Difference between request.ip and request.raw.ip in fastify.

There is a difference only if your server runs behind a proxy/balancer.

Let's make an example:

Client IP: 123.123.123.123 Balancer IP: 10.10.10.10

The request.raw.connection.remoteAddress will be 10.10.10.10 The request.ip will be 123.123.123.123 (only if trustProxy option is enabled) or it will ba as the raw one

Many other ones are just shortcuts such as hostname or url.

Ip example:

Runs locally the Fastify server
{"ip":"127.0.0.1","ipRaw":"","ipRemote":"127.0.0.1"}

Runs behind a ngnix with trust proxy (192.168.128.2 is nginx)
{"ip":"192.168.128.1","ipRaw":"","ips":["192.168.128.2","192.168.128.1"],"ipRemote":"192.168.128.2"}

Runs behind a ngnix without trust proxy (return the caller ip)
{"ip":"192.168.128.2","ipRaw":"","ipRemote":"192.168.128.2"}

You can play with it:

const fastify = require('fastify')({
  logger: true,
  trustProxy: true
})

fastify.get('/', async (request, reply) => {
  return {
    ip: request.ip,
    ipRaw: request.raw.ip || '',
    ips: request.ips,
    ipRemote: request.raw.connection.remoteAddress
  }
})

fastify.listen(5000, '0.0.0.0')
version: "3.9"
services:
    localnode:
      build:
        context: ./
        dockerfile: Dockerfile-fastify
      ports:
        - "5000:5000"
    nginx:
      build:
        context: ./
        dockerfile: Dockerfile
      ports:
        - "8080:80"

Fastify

FROM node:alpine
COPY package.json ./
RUN npm install
COPY ./proxy.js .
EXPOSE 5000
CMD ["node", "proxy.js"]

nginx

FROM nginx
EXPOSE 8080
COPY default.conf /etc/nginx/conf.d/

and the config

server {
  proxy_http_version 1.1;
  proxy_set_header Host $host;
  proxy_set_header Connection "";

  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;

    proxy_pass http://localnode:5000;
  }
}

PS: these docker files are not for production

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community