How to get client IP Address in a Firebase Cloud Function

A simple Firebase Function to get the client IP Address based on the request.


npm i firebase-functions cors --save

Create a new function in your functions/src directory.

import * as functions from "firebase-functions";
const {debug, log, info, warn, error } = functions.logger;

export const ipAddress = functions.https.onRequest( async( req, res ) => {
   const cors = await import ('cors');
   const corsHandler = cors({origin: true});
   corsHandler(req, res, () => {});
   if (req.method === 'OPTIONS') return;
   let ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
   log( `Fetching client ipAddress`, ipAddress );
   res.json( {ipAddress: ipAddress} );
} );