loading...

Deploying An Express Application - 6 Best Practices for Improving Security

blizzerand profile image Manjunath ・6 min read

Deployment is the final phase of software development lifecycle when an application or an API is readily available to consumers and end users. Unlike the development phase where the application is in active development, once deployed, the application could be under potential risks because the endpoints are exposed.

The environments for both development and production generally have a different set up as they have distinct requirements. What is required at the development stage may not be essential when it comes to production. To take an example, in a development stage, a verbose log of errors to help in debugging efforts may have the highest priority, however, at the production stage, security concerns become a priority.

Similarly, at the development stage, scalability, performance or reliability are not areas that you need to address, however, these become critical at the production stage.

In this post, we'll address some of these issues and cover everything that you need know about deployment best practices.

Usage of Deprecated or Vulnerable Versions of Express

If you are still using Express 2.x or Express 3.x, you should know that these are no longer actively maintained or monitored. Therefore, it might not be best idea to use them. In case you have not already moved to version 4.0, you can follow the migration guide here.

Also, you need to make sure that you are not using any versions of Express that are known to be vulnerable. You can see these listed on the Security Updates page – If you are, you need to update to one of the latest stable releases.

Use TLS for Encryption

In case the app you are developing uses sensitive data, it is best to use Transport Layer Security or TLS. TLS can be used to secure your connection as well as data.

TLS encrypts data before it is transmitted from the client to the server. This prevents most common and easy hacks.

Given that Ajax and POST requests at times are not visibly obvious and may seem 'hidden' at the browser level, the network traffic they generate is open to packet sniffing as well as man-in-the-middle attacks. You may already be familiar with SSL encryption, however, TLS can be considered as a more advanced version. I

f you are already using SSL, you might want to consider upgrading to TLS. Our recommendation is that you use Nginx to handle TLS. As a reference you can have a look at- Another useful tool to acquire a free TLS certificate is 'Let's Encrypt' . This is a free, automated and open source certificate authority brought to you by the ISRG, Internet Security Research Group.

Use Helmet For Protection Against Vulnerabilities

Helmet is a handy tool when it comes to protecting your app from commonly known web vulnerabilities. Its safeguard is to ensure the most appropriate setting for HTTP headers.

Coming down to the basics, Helmet is not much more than a collection of 9 smaller middleware functions that define security related HTTP headers. These include –

  1. Csp – Sets the content-security-policy header to assist in preventing cross-site script attacks and various other inter site injections
  2. hidePoweredBy – This eliminates X-Powered-By header
  3. Hpkp – This adds Public Key Pinning headers to prevent any man-in-the-middle attacks using various forged certificates
  4. hsts – hsts sets Strict-Transport-Security headers which enforce secure connections to the server via HTTP over SSL/TLS.
  5. noCache – noCache sets a Cache-Control and Pragma headers to disable any client facing caching
  6. noSniff – This sets an X-Content-Type-Options that can prevent browsers from MIME-sniffing a response generated from a declared a content-type.
  7. frameguard – frameguard sets the X-frame-Options header to allow for clickjacking protection
  8. xssFilter – The xssFilter establishes a X-XSS-Protection that enables Cross-site scripting, or XSS, in the more recent web browsers.

To install Helmet, you can do it as with any normal module –

$ npm install -save helmet

After which, you can now use it in your code via –

// ...
var helmet = require( 'helmet' )
app.use(helmet())

// ...

The Safe Usage of Cookies

In order to make sure that cookies do no expose your apps to malicious attacks, it is recommended that you do not use a default cookie name. However, you can choose to set a predefined cookie security option. These are available in two broad middleware cookie session modules –

  1. Express-session – This replaces express.session middleware built-in to Express 3.x
  2. Cookie-session – This replaces express.cookieSession middleware built-in to Express 3.x

The differentiating factor between these two modules is the method in which they save data from cookie sessions. The Express-session middleware stores its session data onto the server. This saves only the session ID within the cookie and not the session data.

Unless programmed otherwise, the Express-session makes use of in-memory storage capabilities and not is best designed for production environments.

Contrasting the Express-session middleware, the cookie-session middleware makes use of cookie backed storage. It sterilizes the complete session within the cookie, instead of just producing a cookie key. It is advised that this is best used when session is relatively small and easy to encode.

Also, another flag, it is best to be aware that cookie data will be available to the client, therefore, if there is need any need for confidentiality, this is something to keep in mind.

Using the default session cookie name may be a bad idea

If you use the default session cookie name you open your app to attacks. The security flag is similar to X-Powered-By: a potential attacker that fingerprints servers and targets attacks accordingly.

To circumvent this problem, you can use generic cookie names like using express-session middleware:

var session = require('express-session')
app.set('trust proxy', 1) // trust first proxy
app.use(session({
  secret: 's3Cur3',
  name: 'sessionId'
}))

Options for setting cookie security

In order to enhance the security of the following cookie options, you can-

  1. secure – Ensure that the browser only sends the cookie over HTTPS.
  2. httpOnly – This ensures that the cookie is only sent via HTTP(S), and not client JavaScript. This assists in protecting against cross-site scripting attacks.
  3. domain – This indicates the domain of the cookie. Domain can be used to compare against the domain of the host server from where the URL is being requested.
  4. path – This indicates the path of the cookie. Path can be used it to compare against the request path. If there is match found between the path and domain fields, send the cookie in the request.
  5. expires – This is used to specify the expiration date of repetitive cookies.

Below is an example of how a cookie-session middleware can be used:

var session = require('cookie-session')
var express = require('express')
var app = express()

var expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
  name: 'session',
  keys: ['key1', 'key2'],
  cookie: {
    secure: true,
    httpOnly: true,
    domain: 'example.com',
    path: 'foo/bar',
    expires: expiryDate
  }
}))

Avoid Identified Vulnerabilities and Other Securities Issues

As mentioned earlier, it is a good idea to monitor Node Security Project and Snyk updates that may impact the express package and other node modules that your application uses. There are resources that are excellent to stay abreast with the ever-evolving node security. Here are some of the generic security resources that you can use to keep up with the latest trends in security for your Application:

  1. NPM's security blog - NPM's official blog is a great resource to keep yourself up to date with the NPM and Nodejs.
  2. Exabeam's Security Blog - Exabeam's security blog focuses on incident reporting and the steps required to contain the surface area of the vulnerability.
  3. RisingStack Blog - They have an impressive security checklist that you shouldn't miss if you are developing the server using Nodejs.

Ensure All Your Dependencies Are Secure

The usage of Npm to ensure that the dependencies of your application are both robust and convenient is the best you can hope for. However, most developers use packages that may, at times, contain critical security vulnerabilities which can have an adverse in your in-house application.

Since the release of npm@6, npm now automatically reviews each requested installation.

Additionally, you can also use 'npm audit' for analysis –

'$ npm audit'

If you would like to ensure a greater level of security, you can also consider using Snyk.

Snyk provides a command-line tool in collaboration with Github, that can provide audit services for your applications against known open source database vulnerabilities. You can install the CLI below:

$ npm install -g snyk
$ cd your-app
To check your application for vulnerabilities, you can use the following command - 
$ snyk test
You can implement the command below to open a wizard that will apply updates and patches to fix uncovered vulnerabilities as they are discovered:
$ snyk wizard

Summary

We've covered some of the best practices for creating an Express application. The common production phase security best practices include –

  1. Avoid the usage of deprecated or vulnerable versions of express
  2. Use TLS
  3. Use Helmet package
  4. Implement the cookies the safe way
  5. Avoid known vulnerabilities
  6. Ensure all your dependencies are secure & up to date

So, what are your thoughts on securing your Express application? Share them in the comments.

Posted on by:

blizzerand profile

Manjunath

@blizzerand

Founder of Storylens - A content publishing platform for the devs. Amateur musician. Favorite quote? "Being a jack of all trades doesn't mean you're a master at n

Discussion

markdown guide
 

This is great information. B I've never heard of helmet, but it seems like something I'd want to implement in some of my production code!

 

It seems good! I should try it too in some of my projects.

 

Can you explain deeply the snyk usage?
Ty