MonkeyBonkey
MonkeyBonkey

Reputation: 47851

how can I check that a request is coming over https in express

I want force certain routes to always use a secure connection in my express app. How can I check to make sure it is using https?

I am using piggyback ssl on heroku for my deployments.

Upvotes: 6

Views: 5622

Answers (3)

Ben
Ben

Reputation: 1213

app.enable('trust proxy');

"Using Express behind a reverse proxy such as Varnish or Nginx is trivial, however it does require configuration. By enabling the "trust proxy" setting via app.enable('trust proxy'), Express will have knowledge that it's sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed."

Express behind proxies doco

Upvotes: 1

aek
aek

Reputation: 855

I deploy on Heroku as well. They add a bunch of their headers when they use nginx to reverse proxy. The one of interest in this case would be x-forwarded-proto.

This is what I did:

app.get(/\/register$/, function(req, res){
  console.log(JSON.stringify(req.headers)); //to see all headers that heroku adds
  if(req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "http") {
    res.redirect("https://" + req.headers.host + req.url);
  }
  else {
    //the rest of your logic to handle this route
  }
});

Upvotes: 12

Pastor Bones
Pastor Bones

Reputation: 7351

In order to run a secure server (https) it would have to be created independently from a non-secure server (http). They would also listen on separate ports. Try something like this:

var express = require('express)
  , app_insecure = express.createServer()
  , app_secure = express.createServer({ key: 'mysecurekey' })

app_insecure.get('/secure-page',function(req, res){
  // This is an insecure page, redirect to secure
  res.redirect('https://www.mysecuresite.com/secure-page')
})

app_secure.get('/secure-page', function(req,res){
 // Now we're on a secure page
})

app_insecure.listen(80)
app_secure.listen(443)

OR this could be implemented as route middleware

var redirect_secure = function(req, res, next){
  res.redirect('https://mysite.com' + req.url)
}

app_insecure.get('/secure-page',redirect_secure,function(req, res){})

Now you would only have to include the function reference: redirect_secure() on the paths that you would like redirected to a secure location.

Upvotes: 0

Related Questions