How to Use Third-Party Middleware with Express.js and TypeScript

Note: This post is part of Learn How to Use TypeScript With Node.js and Express.js series. Click here to see the first post of the series.

Third-party middlewares are a good alternative when there is a package available out there offering functionality that our API will need such as allowing client access from different origins and parsing the incoming request body data. In this section, we are going to talk about some of the most common middleware use when building Express.js applications.

Using compression Middleware

The compression middleware attempts to compress response bodies for all of the responses.

Why compressing responses is important?

It is important to mention that compressing responses is not required. However, it is an optimization method. For example, an API might receive a request from a web application, in return, the API sends back a response. Sometimes, responses contain a lot of data. When that happens, the response size increases increasing the bandwidth and also increasing the client’s data consumption. This becomes more noticeable in mobile apps as response sizes can dramatically reduce the user’s mobile data.

How to use compression middleware in Express.js with TypeScript?

Let’s start by installing the middleware as part of the dependencies as well as installing its types.

npm i -s compression
npm i -D @types/compression

Open the index.ts in our app. We are going to import the compression and add the middleware using app.use.

import compression from 'compression';

const app = express();
const port = 3000;

// compresses all the responses
app.use(compression());

Using helmet Middleware

Security is important and helmet is a middleware that improves the security of your application.

Helmet helps you secure your Express apps by setting various HTTP headers. It’s not a silver bullet, but it can help!

helmet

First, install the package.

npm i -s helmet

To use helmet, import the package in the index.ts file and add the middleware using app.use. By doing so, it will automatically add 11 of the 15 middlewares that helmet offers.

import helmet from 'helmet';

// adding set of security middlewares
app.use(helmet());

It is recommended to check all the different configuration options provided by the package. If you are not sure, use the default configuration.

Using body-parser Middleware

The body-parser middleware parses all incoming requests body content and adds the information inside the req.body before triggering any handlers. This will be useful especially when working with PUT and/or POST requests.

As usual, we need to install the package first.

npm i -s body-parser
npm i -D @types/body-parser

Add the middleware by importing it in the index.ts file and adding the middleware using app.use.

import bodyParser from 'body-parser';

// parse incoming request body and append data to `req.body`
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Once again, depending on what kind of functionality you add to your API, you might need or not to add additional configuration. For the time being, using bodyParser.json() and bodyParser.urlencoded({ extended: true }) are typically used in most APIs.

Using cors Middleware

There is a high chance your API needs to be accessible from different client origins, for example, from a mobile device, or from a web browser while your API is running in a different server. Unless you allow access to clients to the API, the clients will face CORS errors. That’s why we are going to install the package cors .

npm i -s cors
npm i -D @types/cors

Then we are going to use it by importing it in the index.ts file and adding the middleware using app.use.


import cors from 'cors';
// enable all CORS request 
app.use(cors());

As you noticed in the comments, we allowing all CORS requests. If your application should only allow specific origins, I recommend checking the documentation to set up your whitelist.

After adding all the third-party middleware required for our application to work, your index.ts file should look like the following:

 
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import bodyParser from 'body-parser';
import cors from 'cors';
import routes from './api/routes';

const app = express();
const port = 3000;

// compresses all the responses
app.use(compression());

// adding set of security middlewares
app.use(helmet());

// parse incoming request body and append data to `req.body`
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// enable all CORS request 
app.use(cors());

app.use('/api/', routes);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
}); 

What is Next?

Now that we learnt how to use third-party middleware, it’s time to learn how to use an application-level middleware.

Share this article or checkout our social media channels!