How to get client IP address in a Firebase cloud function?

17,603

Solution 1

If you are looking for the client ip thru firebase hosting you should use the header fastly-client-ip there will be the real client ip.

Solution 2

The clients IP is in request.ip.

Example:

export const pay = functions.https.onRequest((request, response) => {
  console.log(`My IP is ${request.ip}`);
});

Solution 3

The IP address seems to be available in req.headers["x-forwarded-for"].
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

Note that if there are proxies in between the interim ip addresses are concatenated towards the end:

X-Forwarded-For: <client_ip>, <proxy_1 : actual-ip-as-seen-by-google> ...

Solution 4

This worked for me:

const express = require('express');

const logIP = async (req : any, res : any, next : any) => {
    const clientIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.headers['fastly-client-ip'];
}

const logIPApp = express();
logIPApp.use(logIP);

exports.reportIP = functions.https.onRequest(logIPApp);
Share:
17,603
tuomassalo
Author by

tuomassalo

Updated on June 18, 2022

Comments

  • tuomassalo
    tuomassalo about 2 years

    When saving data to Firebase database with a Firebase cloud function, I'd like to also write the IP address where the request comes from.

    However, req.connection.remoteAddress always returns ::ffff:0.0.0.0. Is there a way to get the actual IP address of the client that makes the request?