Skip to content

a method to set req.ip from customized http header #4499

@trim21

Description

@trim21

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

add a method to read ip from customized http header

Motivation

I'm using cloudflare as cdn. cloudflare send client ip with http header cf-connecting-ip

but proxy-addr can only read header from X-Forwarded-*, I hope there can be a new method to set req.ip

Example

import Fastify, { FastifyRequest } from 'fastify';

const fastify = Fastify({
  logger: false,
  genReqIp: (req: FastifyRequest): string => {
    const ip = req.headers['cf-connecting-ip'];
    if (ip) {
      return ip;
    }

    return req.connection.remoteAddress ?? '0.0.0.0';
  },
});


fastify.get('/', function (req, reply) {
  reply.send(req.ip);
});


{
  const { statusCode, payload } = await fastify.inject({
    url: '/',
    headers: { 'Cf-Connecting-Ip': '1.2.3.4' },
  });
  console.log(statusCode, payload);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions