5 Express Middleware Libraries Every Developer Should Know

5 Express Middleware Libraries Every Developer Should Know

Express is the most popular framework when building NodeJS web applications. It is also known as a minimalist unopinionated framework that heavily depends on middleware libraries.

Hence, Express provides a variety of built-in and third-party libraries to achieve basic functionalities.

This article will discuss the top five middleware libraries preferred for any Express web application.

1. Helmet — Increase HTTP Header Security

Helmet helps you secure your Express apps by setting various HTTP headers. It is a quick and straightforward way to create an additional layer of security by switching from Express default headers to more standard ones.

Features of Helmet

  • A Connect-style middleware.
  • It secures your Node.js application from common security vulnerabilities such as clickjacking, implementation of strict HTTP, and download options for vulnerable browsers such as IE8.
  • Instructs browsers to use HTTPS instead of insecure HTTP.
  • In addition, it comes with a way to allow web applications to isolate their origins with Origin-Agent-Cluster header.
  • Has some browser-specific configuration options (helmet.ieNoOpen()for Internet Explorer 8).
Helmet has over 1 million NPM downloads per week and 8.6K GitHub ratings.

Installation

You can install Helmet.js for your Express.js application with the following command.

npm install helmet --save

Then, include it into your app like this.

var express =require('express');
var app =express();
var helmet =require('helmet');
 ​
app.use(helmet());

Usage of Helmet

The top-level Helmet function wraps 15 smaller middlewares. It enables 11 of them by default.

This could be one of the reasons why using Helmet is recommended in the Express.js security best practices.

Let's consider two of these popular configuration options Helmet offers.

contentSecurityPolicy-set the Content-Security-Policy with helmet.contentSecurityPolicy (options) to prevent cross-site scripting attacks. Here is an example of the module in use.

app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      "script-src": ["'self'", "codeacademy.com"],
      "style-src": null,
    },
  })
 );
  • expectCt(options) — mitigate miss-issued SSL certificates. You can choose from three parameters to use.
  • maxAge — defines the number of sections to anticipated Certificate Transparency.
  • enforce — if true, future connections that breach the Certificate Transparency policy should be refused by the user agent. By default, it is set to false.
  • reportUri — If anything goes wrong, it will send a report to the URL provided.

Following is an example for expectCt(options) in use.

app.use( 
    helmet.expectCt({ 
        maxAge: 96400, 
        enforce: true, 
        reportUri: “https://securecoding.com/report", 
    }) 
);

Cookie-parser is a middleware that transfers cookies with client requests.

Cookie-parser uses the req.cookies property to access Cookie data. After parsing, the req.cookies object holds cookies sent by request in JSON format. It is capable of parsing both unsigned and signed cookies.

Features of Cookie-parser

  • The decode function is there to decode the value of the cookie.
  • Handle cookie separation and encoding.
  • Can enable signed cookie support by passing a secret string.
  • supports special "JSON cookies" with JSON.parse.

Installation

Use the following command to install cookie-parser.

npm install --save cookie-parser

Usage of Cookie-parser

After installation, you have to include it in our index.js file to use it.

var cookieParser = require('cookie-parser');
app.use(cookieParser());

Let's create a new route in your Express app to set a new cookie.

var express = require('express');
var app = express();
app.get('/', function(req, res){
   res.cookie('name', 'express').send('cookie set'); 
});
app.listen(3000);

You can use the following command to verify the cookie values on the client side.

console.log(document.cookie);

To view cookies from your server, add the following code to a route in the server console.

console.log('Cookies: ', req.cookies);

As a result, the next time you request this route, you'll get the following response.

Cookies: { name: 'express' }

3. Passport — Access to Wide Range of Authentication Mechanisms

It consists of a comprehensive set of authentication mechanisms known as "strategies." Those strategies support authentication using either a username and password or Facebook, Twitter, and more. Passport allows the developers to make application-level decisions and choose the best strategy, maximizing its flexibility.

Installation

We can install Passport can using NPM as follows:

$ npm install passport

Usage of Passport

Let's consider a simple authentication example with Passport. Here, we must configure the authentication strategy (or strategies) before authenticating any requests.

Below is an example of using LocalStrategy for username/password authentication.

var passport = require('passport'), 
LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

Then to authenticate requests, you have to call passport.authenticate() defining the authentication strategy you choose.

app.post('/login',   
passport.authenticate('local'),   

function(req, res) {     
// If this function gets called, authentication was successful.     // `req.user` contains the authenticated user.     

res.redirect('/users/' + req.user.username);   
});

4. Morgan— Log HTTP Requests and Errors

It streamlines the process by generating logs for each API request and error. The best fact is that you can utilize a predefined format or design one from scratch, depending on your requirements.

Features of Morgan

It Logs the HTTP requests along with some other information. You can also configure what you decide to log.

Very helpful in debugging and also if you want to create log files.

Installation

We can install Morgan via NPM with the below command.

$ npm install morgan

Usage of Morgan

To use morgan in your Express server, you can invoke an instance and pass it as an argument in the .use() middleware before your HTTP requests.

  1. Using predefined formats — Morgan has predefined format strings to configure the middleware with built-in formatting and options.

Ex: The preset tinyprovides a minimal output when logging HTTP requests.

const app = express();
app.use(morgan('tiny'));
  1. Using a custom format- Morgan allows you to create custom tokens with the .token()method.
morgan.token('host', function(req, res) {
    return req.hostname;
});

5. CORS — Allow or Restrict Requested Resources on a Web Server

CORS stands for Cross-Origin Resource Sharing. Without prior consent, it prevents other websites or domains from accessing your web resources directly from the browser.

Features of CORS

Supports GET, POST, or HEAD HTTP methods. Allows web programmers to use regular XMLHttpRequest, which handles errors better. Allows websites to parse responses to increase security.

Installation

You can install it using the npm install command:

npm i --save express
npm i --save cors

Usage of CORS

You can use either enable CORs for all the routes or only for a single route.

  1. Enable All CORS Requests
const express = require('express'); 
const cors = require('cors');
const app = express();
app.use(cors())  
......
  1. Enable CORS for a Single Route
app.get('/', cors(), (req, res) => {     
res.json({         
message: 'Happy Coding'    
 }); 
});

Conclusion

In this article, I discussed five different Express middleware libraries. Each of them has its advantages and drawbacks. It is up to you to choose the best library as per your project requirements.

So, I hope my recommendations will help you make a wise decision in selecting Express middleware libraries for your next project. And don't forget to share your experience in the comment section if you have already used them.

Thank you for Reading !!

Follow our official website braincuber.com

Did you find this article valuable?

Support Braincuber Technologies Pvt Ltd by becoming a sponsor. Any amount is appreciated!