Home

Node.JS api to get User IP Address and additional user info

Setup:

Get secret key from ipdata. You need this if you want additional user info. You can skip this if you don't need the additional user info. The api will return just the user IP in that case.
npm install —save ipdata

if you are using typescript you might face an error
Could not find a declaration file for module 'lru-cache'.
To resolve in your functions folder install
npm install —save-dev @types/lru-cache

You might face another error at this point if you are using typescript:
Module '"/YOUR-PATH/functions/node_modules/@types/lru-cache/index"' can only be default-imported using the 'esModuleInterop' flag

Navigate to
/YOUR-PATH/functions/node_modules/@types/lru-cache/index.d.ts

Change last line from
export = LRUCache;
To
export default LRUCache;

Code:

import IPData from 'ipdata';
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const axios = require("axios");
import * as cors from "cors";
const corsHandler = cors({ origin: true });

admin.initializeApp({
credential: admin.credential.cert(
Object.assign(
{
private_key: "your-server-private_key",
},
functions.config().serviceaccount
)
),
databaseURL: "your-firebase-db-url",
});

exports.userInfo = functions.https.onRequest(async (request, response) => {
corsHandler(request, response, async () => {
let secret = functions.config().ipdata.key; //your ipdata secret key)
const user_ip = request.headers["x-forwarded-for"] || request.connection.remoteAddress;
try {
const ipdata = new IPData(secret);
const result = await ipdata.lookup(String(user_ip))
const data = result;
if (data) {
response.status(200).send({ user_ip: user_ip, additional_info: data })
} else {
if (user_ip) {
response.status(200).send({ user_ip: user_ip, error: 'No additional info', errorText: 'Getting additional info failed' })
} else {
response.status(400).send({ error: 'Could not get user ip', errorText: 'User ip not found' });
}
}
} catch (error) {
functions.logger.log("error: ", error);

if(user_ip) {
response.status(200).send({
user_ip: user_ip,
error: error, errorText: 'Internal Error but found user ip' });
} else {
response.status(500).send({ error: error, errorText: 'Internal Error' });
}

}
});
});


comments powered by Disqus