Skip to content

Using Middleware with Express (and TypeScript)

Node.js, Express, TypeScript1 min read

Middleware serves as a crucial component in the world of web development, particularly when working with frameworks like Express in the Node.js ecosystem. In this article, we will delve into the concept of middleware, explore its significance, and learn how to implement it in an Express application using TypeScript.

Understanding Middleware

Middleware can be thought of as a bridge that connects incoming HTTP requests to the corresponding response. It functions as a pipeline through which a request passes, allowing us to perform various operations such as authentication, logging, error handling, and more - before hitting the actual route.

Implementing Middleware with Express and TypeScript

Let's begin by setting up an Express application with TypeScript support. First, ensure that you have Node.js installed on your machine along with npm or yarn. Create a new directory for your project and initialize it with a package.json file by running npm init or yarn init. Once that is done, install the necessary dependencies:

1npm install express @types/express typescript ts-node --save

We also need to create a tsconfig.json file to configure TypeScript for our project. Here's a minimal example of what the file might look like:

2 "compilerOptions": {
3 "target": "ES2018",
4 "module": "commonjs",
5 "outDir": "./dist",
6 "strict": true,
7 "esModuleInterop": true
8 }

Next, let's create a basic Express server file app.ts in the root of our project:

1import express, { Request, Response, NextFunction } from "express";
3const app = express();
5// Middleware function
6function loggerMiddleware(
7 request: Request,
8 _: Response,
9 next: NextFunction
10) {
11 console.log(`[${new Date().toISOString()}] ${request.method} ${request.url}`);
12 next();
17app.get("/", (_: Request, response: Response) => {
18 response.send("Hello, World!");
21const port = 3000;
22app.listen(port, () => {
23 console.log(`Server is listening on port ${port}`);

In the example above, we defined a simple logging middleware function called loggerMiddleware. This function logs the timestamp, HTTP method, and URL of every incoming request before passing control to the next middleware function in the chain. We then applied this middleware globally to our Express application using app.use(loggerMiddleware). As you may also see we have imported the types for 'Request', 'Response' and 'NextFunction' from the 'express' package.

Bonus: Middleware for specific routes

Also keep in mind that you can also pass a middleware function to a specific route instread of using it globally, for example you could add loggerMiddleware just to the '/' route by remove the app.use call and adding changing the code for the route to this:

1app.get("/", loggerMiddleware, (_: Request, response: Response) => {
2 response.send("Hello, World!");

In any case, your requirements will come down to your actual project. As always, happy coding!