Search code examples
node.jshttp-redirectexpressredirect-loop

Redirect loop when setting port via environment variable in forcedomain (node.js, express)


I use forcedomain middleware in my node.js application with express framework to get redirects to default domain.

When I specify port in forcedomain settings explicitly, it works well, for example in a trivial 'hello world' application:

var express = require('express') 
var app = express() 
var forceDomain = require('forcedomain') 

app.use(forceDomain({ 
    hostname:'example.com', 
    port:3000 
})) 


app.get('/', function (req, res) { 
      res.send('Hello World') 
}) 

app.listen(3000)

But then I decided to set all configurable variables via environment (i.e., to have different ports in development or production mode). So I changed the cited above code - replaced 3000 with process.env.PORT:

...
app.use(forceDomain({ 
    hostname:'example.com', 
    port:process.env.PORT 
}))     
...
app.listen(process.env.PORT)

and run the application as following

$ PORT=3000 node app.js

But this time, if I enter http://example.com:3000 in browser, I get an redirect-loop error: "This webpage has a redirect loop (ERR_TOO_MANY_REDIRECTS)"

I tried to use dotenv package to load environment variables from .env file, and added the following at the beginning of my application:

require('dotenv').load()

but result was the same - redirect loop.

It looks like app.listen gets the proper value from process.env.PORT, while forcedomain doesn't and starts with default port setting (80).

So this question is still open to me: how to pass the env. variable to forcedomain settings?

update1

Versions are fresh:

$ node -v
v0.12.2
$ cat package.json
{
  "name": "forcedomain-test",
  "version": "0.0.1",
  "devDependencies": {},
  "dependencies": {
    "dotenv": "^1.2.0",
    "express": "^4.13.0",
    "forcedomain": "^0.4.0"
  }
}

Solution

  • Try this:

    app.use(forceDomain({ 
      hostname : 'example.com', 
      port     : Number(process.env.PORT)
    }))
    

    forceDomain does a strict match against the port number in use (which it turns into a number first) and the port set in the options (which, because it's coming from an environment variable, is a string).

    Since strings and numbers don't match when performing strict equality checking, forceDomain thinks it has to issue a redirect.