8

5 Express Middleware Libraries Every Developer Should Know

 2 years ago
source link: https://blog.bitsrc.io/5-express-middleware-libraries-every-developer-should-know-94e2728f7503
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

5 Express Middleware Libraries Every Developer Should Know

Recommended Express middleware libraries

Express is the most popular framework when building NodeJS web applications. It is also known as a minimalist unopinionatedframework 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.
  1. maxAge — defines the number of sections to anticipated Certificate Transparency.
  2. 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.
  3. 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",
})
);

2. Cookie-parser — Parse Cookies

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.

Cookie-parser has over 407K NPM downloads per week and 2K GitHub ratings.

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

Passport is a simple unrobustive authentication middleware for Node.js.

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.

Features of Passport

  • 500+ authentication strategies.
  • Extremely easy to integrate into an application.
  • Single Sign-on with OpenID and OAuth.
  • Supports persistent sessions.
  • Lightweight code base.
  • Let you implement custom strategies.

Passport has over 1 million NPM downloads per week and 19.5K GitHub ratings.

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

Morgan is an HTTP request logger middleware for Node.js typically used for Express apps.

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 choose to log.
  • Very helpful in debugging and also if you want to create Log files.

Morgan has over 12.88 million NPM downloads per month and 6.8K GitHub stars.

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'));

2. 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 is a node.js package that provides a Connect/Express middleware for enabling CORS with a variety of options.

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.

CORS has over 6 million NPM downloads per week and 5.2K GitHub ratings.

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())
......

2. Enable CORS for a Single Route

app.get('/', cors(), (req, res) => {     
res.json({
message: 'Happy Coding'
});
});

Note: You can also use the CORS configuration options for further customizations.

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared "card" component. On the right => its dependency graph, auto-generated by Bit.

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 !!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK