Should you use Express-session for your production app?
Tags: opensource, webdev, authentication, oauth
Published: 2020-05-19 15:13:54

While being Node’s most popular session management library, express-session has its set of flaws and weaknesses – especially when it comes to security. This article will analyze the good and bad parts of express-session so that you can make an informed decision for your next app. We will be using a point system where one point will be awarded for performing well on a metric, and one will be deducted for bad performance. At the minimum, we want a positive number at the end of the analysis (and the higher the number is, the better). Here are the metrics we will be using:

- Security: This is especially relevant because we’re talking about user session management.
- Reliability and Correctness: It is imperative that the library takes care of technical issues like keeping its state consistent despite of network or server failures and taking care of synchronising its logic in a clustered environment.
- App User experience: We want to use a library that can provide the right experience for your app users – for example, does the library enable a user to be logged in for weeks or months whilst also providing good security?
- Time to production: We will look at factors such as time to integrate the library into an app, available support, and ease of understanding of the library code.
- Maintenance cost: We will assess costs of maintaining the library over time.

## __Security:__

![session security image](https://lh5.googleusercontent.com/uXt_ED-AfE7JYkVwUYrjdVowpvUu5sIUDGoNpeYvwQZJJXFUhoNqNmRpMvS7K4ARs6_F5gfKQ9MNF9GxZczOL2hVI2yg7KtQ4n_Db4tGDLll8DIvCRWeGHyg0CC_shmg0knvIbtj)

For a background on why session security is important, read our [other blog post](https://bit.ly/3fXi366) (Facebook, Docker, Gitlab have all had session vulnerabilities in the past 2 years). Session attacks can occur across 3 attack vectors; the frontend, in transit (over the internet) or on the backend.

## __Token theft via XSS:__

In an XSS attack, an attacker can maliciously inject JavaScript code into an application running on the victim’s browser. The injected code reads and transmits auth tokens to the attacker. 

Exclusively using cookie storage to store auth tokens and setting their HttpOnly flag to true disallows any JavaScript running on the browser from reading them, preventing token theft via XSS. We give one point here.

__Score: 1__

## __Brute force:__ 
![Brute force image](https://lh6.googleusercontent.com/CWOM9O57kwlwUEuW092TPUATICOhQip4EsY-LbxxtHP_8_t0hsxSpdwPyEAS8TB6Vdnr3GmtQKhobJPOFC3QK0Q7O2icS12DGlp2PIgOCOOQRFP4h4fFxBtIXX4Zpv-nKBM4_2MY)

This attack can be solved easily by using long auth tokens that have a high level of entropy.

Express-session prevents this attack by default and hence receives a point.

__Score: 2__

## __Token theft via Man in the middle attack:__

![Token theft via Man in the middle attack image](https://lh6.googleusercontent.com/YhBM1WWeh--FC4Tb2sUOTbWt98EbJxAJ15aJ5TUpB5Oqb284WFXNsJw1EJcWm01A_fyLzdgXUeft_1b-NU2dPTwWHK20phal9KtJs9KvuN501CL1t6QdJCgSikyyo7cSplniNXb8)

While this attack is mostly preventable using HTTPS, it can still be successfully executed – especially in corporate environments (Check out [this](https://mitmproxy.org/) tool) where access to the internet is controlled via a proxy. As such, there is no full proof method to prevent this attack and we can only attempt to minimise the damage.

Express-session uses just one long lived access token (Session ID). Hence, for each API request, the frontend needs to send this one token to the backend for authentication purposes. If a MITM attack is being carried out, any request the app makes will expose this critical token to the attacker who can then use it to gain access to the victim’s account for a long period of time – potentially months.

Other solutions exist where two tokens are used – access and refresh tokens. These are more secure because the critical token (refresh token) is exposed very rarely. Hence, express-session loses a point.

__Score: 1__

## __Session fixation:__ 
The attack consists of inducing a user to authenticate themselves with a known session ID, and then hijacking the user-validated session by the knowledge of the used session ID. 

Session fixation can be prevented by changing the auth tokens upon successful user login.

While express-session provides the regenerate function, it’s the developer’s responsibility to call this at the right time and make sure any session data is carried forward. Since many developers use passport JS (which doesn’t call this function – see [here](https://github.com/jaredhanson/passport/issues/192)) for login purposes, this attack goes unresolved. 

Hence express-session loses a point.

__Score: 0__

## __Data theft from database:__ 
Express-session stores all SIDs in plain text along with its data. This means that if an attacker was to get hold of this information (and assuming that they also got hold of the secret – which is quite probable if they have access to the db), they could easily hijack the session of all currently logged in users.

In comparison, other libraries like store the hashed version of session tokens in the database.

Express-session loses a point.

__Score: -1__

## __CSRF (Cross-site Request Forgery):__ 
Express-session does nothing to prevent this, nor does it do anything to “remind” developers about this problem. In comparison, other solutions enforce CSRF protection when verifying a session.

__Score: -2__

## __Session hijacking:__

There are two aspects to this attack:

- Preventing unauthorised access via token theft: In theory, it’s impossible to prevent this since the session tokens are being sent to an untrusted client (the app’s frontend). We can only minimise the probability of this event. One of the most prominent methods to do so is to use frequently changing session tokens.
- Detecting token theft and taking appropriate action: Traditional methods of theft detection include methods like analysing IP address or device fingerprint changes. However, these methods lead to many false negatives and positives. The better way to do this is to use the concept of rotating refresh tokens as suggested by IETF in their [OAuth spec](https://tools.ietf.org/html/rfc6749#section-10.4)[1]. After detection, the session solution should allow for immediate or quick revocation of the affected session.

Express-session uses one long lived token and has no means to detect token theft. Below is the session flow for express-session:

![Session flow for express-session image](https://lh3.googleusercontent.com/4IZvipclV20-4lrBXThyc6eURwP57-NB3NdFDpnKEQfZKHS8qhRrM3ubAk1JVucOdlO7G_Nk2Y_3IWIJwYqgewMMVJvB2wjc2taspohKPcUVC3s4OQrdWClFerirb4A4VUAI5N_2)

Clearly, Express-session loses a point here as well:

__Score: -3__

## __Reliability and Correctness:__
Correctness means that the code works as expected in normal and edge case situations. Based on our evaluation, we found that __express-session is not thread safe.__ The specific failure case is that it is possible to bring back a revoked user session in certain scenarios. One example is as follows:

1. A user session is created for  user1
2. Let’s say we have two requests (A and B) sent at the same time from user1. 
3. Request A, reaches the server first and gets the session object in its API. 
4. After that, request B reaches the server and revokes this session (request B could be logout). 
5. Request A then (using its already obtained session object in step 3), modifies some session data and then saves that.
6. This results in the revoked session being alive again.

__Score: -4__

## __App User experience:__

In the context of sessions, a good user experience means that we enable long lived sessions so that app users do not have to keep logging in again and again. Express-session allows for such behaviour.

__Score: -3__

## __Time to production:__

![Time to production image](https://lh5.googleusercontent.com/9-uhfxD7SbFbrZX3ol3ZmXgLKRhMi-ajLXHGFmqO5Ot4PtUZzqF8tOCOK9VtQ7mu6-eeLyh1_PiMIqod9NAqxKQqtv-O-LCIOBzrbpOaw_RzgfEjifwt8hvD8RGU4gcVOc70ECer)

__Completeness:__ Session management is tightly tied to user management. This means, given a session, one should be able to retrieve the associated user information, and given a user ID, one should be able to retrieve all the associated sessions (for example, to display all the list of devices they are currently logged in with). While express-session allows you to go from sessions to users, going the other way around would require customisations and understanding of how the library is implemented. 

__Score: -4__

__Complexity in initial setup:__ Express-session is very simple to set up. One can simply run an install command using npm. Additionally, given that Express as a whole is an extensive framework used by developers, the easiest solution would be to go with express sessions. However, one could also argue that in certain frontend clients (like React Native), handling cookies reliably can be quite difficult. Overall, Express-session is not complex and a point is awarded here.

__Score: -3__

__Community support:__ With close to 800K monthly downloads on npm, it is amongst the most popular session management libraries for node. Hence, it receives a well deserved point here.

__Score: -2__

## __Maintenance costs:__

![Maintenance costs image](https://lh5.googleusercontent.com/KXhK_n6TFsiIou12-aBVzdO9khIEP_-tKTxh4uDwQoaRvR_7iNjtvCcVW7R9n3tZ5YPKn8YPBkMfzjoKlaMZI5j05ITYbSiTxnxGCOF4DUNx_M8HPNRzcIlYcUMeK4gVReGqFCbF)

Can do something similar to time to production. Instead of a stopwatch, we show a spanner and servers

Express-session is a relatively simple library, which means that as apps scale, eventually, more and more work needs to be put into “scaling” / changing the session management system. Examples of changes are:

- Building infrastructure to be able to monitor / revoke sessions in real time from a dashboard.
- Quite often, the API layer is built using multiple frameworks (like NodeJS). Hence, a cost here is to build a library for another backend framework that is compatible with Express-session.
- Adding a caching layer to session to improve performance.
- Adding more functionality to the core session logic:
  - Enhancing security by revoking sessions based on changes in device fingerprints or IP addresses.
  - Syncing session data across a user’s devices. 
  - Implementing different session timeouts for different user roles.

I realise that not all the above points will be of concern, but even if one of them does end up being true, that can add significant costs to an organisation / project simply because of how expensive developers are – especially one experienced enough to work on session security. 

__Score: -3__

### __Conclusion__

Express-session is a popular, widely used library. It is basic, functional and quick to setup – and for many applications, this is good enough. However, it seriously lacks in other important aspects. For many applications, security is rightfully an important consideration and express-session is far too basic. Aside from security, it lacks functionality and does not adequately consider race conditions. These factors become important as your app starts to scale.

After speaking to 100+ companies, we observed that close to 75% of startups and enterprises end up building a custom solution to manage user sessions. Many do it for the reasons highlighted above.

With a negative final score, it’s clear that Express-session is not optimal for production apps – especially ones that care about user security and will likely scale with time. If you feel that I have judged unfairly, or missed out an important metric, please do comment or send us an email(team@supertokens.io).

There are many alternatives to Express-session and it is likely that you are considering building a custom solution. However, as an alternative to Express-session, we have built a secure, open source and feature complete solution called [SuperTokens](https://bit.ly/2ZkO3LQ). It is already being used by 100s of developers all. We’d love to hear your feedback on whether this is something you would use.

To learn more about Sessions, please visit our other blogs:

- [All you need to know about session management](https://bit.ly/3fXi366)
- [The best way to securely manage user sessions](https://bit.ly/3e4S5vB)

Written by the Folks at [SuperTokens](https://bit.ly/2ZkO3LQ) — hope you enjoyed!

### __Footnotes__
[1]: Technically, OAuth is different from session management (in the context of this article). But the underlying mechanism through which access is maintained, is similar.