How to get current domain address in sails.js

node.js, sails.js

Solution

Just to preface this answer: there is no reliable, cross-platform way to automatically detect the external URL of a running Sails app (or any other Node app). The `getBaseUrl()` method described below uses a combination of user-supplied and default configuration values to make a best guess at an app's URL. In mission-critical situations, you are advised to pre-determine the URL and save it in a custom environment-dependent configuration value (e.g. `sails.config.appUrl`) that you can reference elsewhere in the app.

If you're on Sails >= v0.10.x, you can use `sails.getBaseurl()` to get the full protocol, domain and port that your app is being served from. Starting with Sails v0.10.0-rc6, this also checks the `sails.config.proxyHost` and `sails.config.proxyPort`, which you can set manually in your one of your config files (like `config/local.js`) if your app is being served via a proxy (e.g. if it's deployed on Modulus.io, or proxied through an Nginx server).

Sails v0.9.x doesn't have `sails.getBaseurl`, but you can always try copying the code and implementing yourself, probably in a service:

getBaseUrl

function getBaseurl() {
  var usingSSL = sails.config.ssl && sails.config.ssl.key && sails.config.ssl.cert;
  var port = sails.config.proxyPort || sails.config.port;
  var localAppURL =
    (usingSSL ? 'https' : 'http') + '://' +
    (sails.getHost() || 'localhost') +
    (port == 80 || port == 443 ? '' : ':' + port);

  return localAppURL;
};

you'll notice this relies on `sails.getHost()`, which looks like:

function getHost() {
  var hasExplicitHost = sails.config.hooks.http && sails.config.explicitHost;
  var host = sails.config.proxyHost || hasExplicitHost || sails.config.host;
  return host;
};

Problem

I trying to get current web address using sails.js. I tried the following: ``` req.param('host') and req.param('X-Forwarded-Protocol') ``` returns undefined. ``` req.headers.host ``` returns localhost. but my domain is not localhost. How to get it ??

Original source