Express: Middleware

A middleware is a function that hooks into the routing process, performing an arbitrary operation at some point in the chain (depending on what we want it to do).

It’s commonly used to edit the request or response objects, or terminate the request before it reaches the route handler code.

Middleware is added to the execution stack like so:

app.use((req, res, next) => { /* */ })

This is similar to defining a route, but in addition to the Request and Response objects instances, we also have a reference to the next middleware function, which we assign to the variable next.

We always call next() at the end of our middleware function, in order to pass the execution to the next handler. That is unless we want to prematurely end the response and send it back to the client.

You typically use pre-made middleware, in the form of npm packages. A big list of the available ones can be found here.

One example is cookie-parser, which is used to parse cookies into the req.cookies object. You can install it using npm install cookie-parser and you use it thusly:

const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Server ready'))

We can also set a middleware function to run for specific routes only (not for all), by using it as the second parameter of the route definition:

const myMiddleware = (req, res, next) => {
  /* ... */

app.get('/', myMiddleware, (req, res) => res.send('Hello World!'))

If you need to store data that’s generated in a middleware to pass it down to subsequent middleware functions, or to the request handler, you can use the Request.locals object. It will attach that data to the current request: = 'Flavio'

Lessons in this unit:

0: Introduction
1: Introduction to Express
2: Request parameters
3: Send a response to the client
4: Send a JSON response
5: Manage cookies
6: Work with HTTP headers
7: Handling redirects
8: Routing
9: Template engines
10: ▶︎ Middleware
11: Serving Static Assets with Express
12: Send files to the client
13: Sessions
14: Validating and sanitizing input
15: Handling form data
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!