NodeJS HTTPS guard with AWS ELB

Running NodeJS behind ELB and proxying https? What happens if someone didn’t configure TLS? Now your app is processing sensitive data over the clear web. What a bad idea! Catch it in code instead.

First when your app is being set up, trust the first proxy.

app.set('trust proxy', 1) // trust first proxy

Then use this middleware. This will only let things pass if the protocol is secure or if the requester is local. It will also return a positive health check to ELB. Otherwise, always redirect.

// security guard to make sure that the application is secure by default
app.use(function(req, res, next) {
if(req.protocol === 'https') {
return next();
}

var localdev = req.headers['host'] === 'localhost'; // flag for local development

if(localdev) {
return next();
}

// health ping from ELB
if (!req.connection.encrypted && !req.headers["x-forwarded-proto"]) {
res.sendStatus(200);
return;
}

// default does a redirect to the secure host
res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});
res.end();
});