Let's follow these steps to secure our Express application:
- First, we will create a custom Express launch script configured to use HTTPS. You can duplicate the /bin/www launch script and make the following adjustments to it:
#!/usr/bin/env node
var https = require('https');
var fs = require('fs');
var app = require('../app');
var debug = require('debug')('my-express-project:server');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var options = {
key : fs.readFileSync('key.pem'),
cert : fs.readFileSync('cert.pem')
};
var server = https.createServer(options, app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
- The easiest way to use this new Express launch script is to create a new npm script alias in our /package.json file:
{
"name": "my-express-project",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"start:https": "node ./bin/https"
},
...
- Now, we can launch an HTTPS secured version of our web server by running npm run start:https. To view our web server, we will need to visit https://localhost:3000. You will see an error from your browser if you are using your self-generated certificate. You can bypass this error by choosing to proceed past the error notification in your browser.
- Next, we should include helmet into our /app.js Express configuration as middleware:
...
var helmet = require('helmet');
...
app.use(helmet());
...
...
- Finally, we will need to update our express-session configuration to further secure our cookies. We can do this by adding a non-default name property to our session, as well as a cookie configuration object:
app.use(session({
secret: process.env.cookieSecret,
resave: false,
saveUninitialized: true,
name: 'project-session',
cookie: {
secure: true,
httpOnly: true,
domain: 'localhost',
expires: new Date(Date.now() + 60 * 60 * 1000)
}
}));
- Now, when we run our application, if our cookies aren't sent via an encrypted HTTPS request, or they come from a domain other than the localhost, they will be considered invalid.