'How to get client IP address in a Firebase cloud function?
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?
Solution 1:[1]
The clients IP is in request.ip.
Example:
export const pay = functions.https.onRequest((request, response) => {
console.log(`My IP is ${request.ip}`);
});
Solution 2:[2]
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 3:[3]
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);
Solution 4:[4]
If you are looking for ip address or headers in cloud callable function, then you can get information inside context object.
for ex:
exports.testUser = async (data, context) => {
console.log('------------------------::context::------------------');
if(context.rawRequest && context.rawRequest.headers){
console.log(context.rawRequest.headers);
}
}
In the headers you can get ip : header { 'x-appengine-user-ip' : 'xxip' } etc.
Solution 5:[5]
This is what worked for me using Firebase Cloud Functions:
const clientIP = req.headers['x-appengine-user-ip'] || req.header['x-forwarded-for']
Note, that this doesn't work locally!
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 | Luke |
| Solution 2 | Ujjwal Singh |
| Solution 3 | hellmit100 |
| Solution 4 | |
| Solution 5 | George Chalhoub |
