The Problem:

You need to get the client IP address in the Cloud Code for Geolocation or similar purposes?

It used to be more complicated, now we can just use the request headers as the update below describes.

Update 2017-10-10

There seems to be a fix in Parse server that allows us to read the headers without this workaround.

If you have a recent version of Parse server, you should be able to simply access the visitor IP through x-forwarded-for request header.

Remember, the x-forwarder-for is sometimes a comma separated list. Quote from the wikipedia article: > the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from”

So be sure to use something similar as below function to avoid having mysterious errors in your backend code:

function getUserIP(request) {
  var forwardedFor = request.headers['x-forwarded-for'];
  if (forwardedFor.indexOf(',') > -1) {
    return forwardedFor.split(',')[0];
  } else {
    return forwardedFor;
  }
}

This one takes the leftmost IP if there is a comma in the header.

If you are using older version of parse server that doesn’t yet support passing the request headers to cloud functions, please upgrade or keep reading on.

The hack we used to need for the older version of Parse server

There’s a little workaround we can deploy here: After all, the parse-server itself runs under express.js, meaning we can transfer stuff that express.js knows, to Cloud Code, through request headers.

Express.js middleware

Assuming that you are running Parse Server from your own .js file, set up this nifty little express.js middleware, somewhere before the app.use('/parse', api); line:

app.use(function(req, res, next) {
  req.headers['x-real-ip'] = req.ip;
  next();
});

Hint: Always remember the next() call in your middleware functions.

Cloud Code part

After that in your cloud code function (file parse/main.js) you can read the IP from the header called x-real-ip thats included in the Cloud Code request.

Parse.Cloud.define('geoLookup', function(request, response) {
  var clientIP = request.headers['x-real-ip'];
});

Isn’t that sneaky?

Remember to restart the node.js process after the changes.

Still Having Issues?

Use the comments section below ☺