Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 833
MonkeyBonkey Avatar asked Nov 16 '11 13:11

MonkeyBonkey


2 Answers

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
  }
});
like image 113
ant Avatar answered Sep 25 '22 15:09

ant


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

like image 27
Ben Avatar answered Sep 24 '22 15:09

Ben