DEV Community

Corey Cleary
Corey Cleary

Posted on • Updated on • Originally published at coreycleary.me

Express-approved middlewares to use in your API

Originally published at coreycleary.me. This is a cross-post from my content blog. I publish new content every week or two, and you can sign up to my newsletter if you'd like to receive my articles directly to your inbox! I also regularly send cheatsheets and other freebies.

When you’re starting up an Express project, it can be confusing to figure out all the modules you need…

…and this is no different when it comes to middleware.

It doesn’t help that – out of the box – Express is “batteries not included.”

Express just isn’t very opinionated. It provides that base and you’re left to piece the rest of the project together.

On the other hand, this freedom Express provides can be seen as one of its strong suits.

But when you just want to start building features instead of wasting time figuring out what middleware you need to include to set up your project, it can feel like you’re spinning your wheels.

You might be wondering – “Am I even following best practices?”

The good news is there are some great resources that do provide you some guidance. One of those – often overlooked – resources is the Express-approved middleware list.

Instead of having to piece together a list of modules by asking on forums for module recommendations or looking through 10 different tutorials, this is a “pre-vetted” list straight from the Express team themselves.

There are a lot of modules listed in the documentation, so it’s too much to cover all of them, but I’ll talk about a few that I use in most of my Express REST API’s, and when you might need to use them in your project.

body-parser

Extracts the entire body portion of an incoming request and exposes it on req.body. Basically, you need this to work with/read the POST body sent to your REST API.

UPDATE 3/2/20: If you are using Express version 4.16.0 onwards you apparently don't need to install the body-parser module separately anymore. The Express team moved it back into Express. In setting up your middlewares, you just have to do app.use(express.json()) and (if you want to parse incoming requests with urlencoded payloads) do app.use(express.urlencoded({ extended: true })) immediately following that.

cookie-session

Used to store the session data on the client within a cookie (as opposed to storing the session data on the server, with a reference to the session ID in the client-side cookie).

If I’m just going to be storing something simple like a user’s name and nothing else, then I’ll go with this module (as opposed to the server-side “session” module) and keep that in the cookie client-side. But usually I’m working with more sensitive and/or more complex information, so I more often use the server-side session module.

*See note below for further guidance on when to use the “session” vs “cookie-session” modules.

cors

In my experience it’s difficult to get away with not using CORS. If you have multiple different sites that will be making HTTP requests to your server, or a different server with the same host but a different port (http://localhost:3000 to http://localhost:4000, for example), you’ll need to enable CORS.

This post goes into much more detail on CORS and scenarios in which you need to enable it.

The good news is you don’t have to enable CORS for everything. You can pass options to the CORS Express module and use a whitelist, as described here.

morgan

You might have logging set up for errors and things like that, but this will log the whole HTTP request.

If you’re wondering why this is useful, consider a time you might have had another service talking to your Node service and it kept failing for some reason (maybe a 400 BAD REQUEST error). Logging the request would allow you to see what is actually being sent to your service – invaluable for troubleshooting.

Just make sure you mask any Personally Identifiable Information like SSN’s.

multer

Used when you have a request containing a “multipart/form-data” Content-Type header.

In layman’s terms – whenever you need to enable uploading of files from a form.

serve-static

Good if you want to publicly serve something like example documentation that lives close to your server-side code. OR, if you are working on a sample project and want to serve up your static assets.

If you want an even more basic setup to serve static files and don’t want to bother with this module, you can use Express’ built-in express.static (more info here).

But for production-level apps, I much prefer using a reverse proxy like nginx or HAproxy to serve static files. You can even take it a step further and use a dedicated CDN (Content Delivery Network) to serve the static files (the purpose of a CDN is to focus only on delivering static assets).

session

Allows you to create a cookie in the browser with only a reference to a unique session ID + setups the session data server-side.

This module supports storing the session data within a large number of stores. See the compatible list here.

*See note below for further guidance on when to use the “session” vs “cookie-session” modules.

**See note below about using this with the cookie-parser module.

Notes

  • cookie-session vs. session – The cookie-session README.md has good guidance on when you might use cookie-session:

  • cookie-session does not require any database / resources on the server side, though the total session data cannot exceed the browser’s max cookie size.

  • cookie-session can simplify certain load-balanced scenarios.

  • cookie-session can be used to store a “light” session and include an identifier to look up a database-backed secondary store to reduce database lookups.

But as noted above, I typically use session.

** cookie-parser – this module is not needed if you’re using the session middleware module.

Lastly, a note on the compression middleware module: the express middleware page lists this module as an option for gzip compresson, but – much like serving static files – I prefer to do this at the proxy/network layer rather than the app layer (using nginx or HAproxy).

And if you have a high-traffic site, doing compression at the reverse proxy layer is almost mandatory.

Wrapping up

The official Express docs have lots of good information, especially on things like production best practices. I encourage you to check them out if you haven’t before! They’re often overlooked.

Love JavaScript but still getting tripped up by architecture stuff and how you should structure your service? I publish articles on JavaScript and Node every 1-2 weeks, so if you want to receive all new articles directly to your inbox, here's that link again to subscribe to my newsletter!

Top comments (2)

Collapse
 
drozerah profile image
Drozerah

Something about template engines ? hbs vs express-handlebars for instance ?

Collapse
 
ccleary00 profile image
Corey Cleary • Edited

I think those wouldn't necessarily be considered "middleware" (like request/response handling middleware). More "engines"