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

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);

The clients IP is in request.ip.

Example:

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

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.


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> ...