Writing middleware for use in Express apps (2024)

Overview

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

The following figure shows the elements of a middleware function call:

Writing middleware for use in Express apps (1)

HTTP method for which the middleware function applies.

Path (route) for which the middleware function applies.

The middleware function.

Callback argument to the middleware function, called "next" by convention.

HTTP response argument to the middleware function, called "res" by convention.

HTTP request argument to the middleware function, called "req" by convention.

Starting with Express 5, middleware functions that return a Promise will call next(value) when they reject or throw an error. next will be called with either the rejected value or the thrown Error.

Example

Here is an example of a simple “Hello World” Express application.The remainder of this article will define and add three middleware functions to the application:one called myLogger that prints a simple log message, one called requestTime thatdisplays the timestamp of the HTTP request, and one called validateCookies that validates incoming cookies.

const express = require('express')const app = express()app.get('/', (req, res) => { res.send('Hello World!')})app.listen(3000)

Middleware function myLogger

Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named myLogger.

const myLogger = function (req, res, next) { console.log('LOGGED') next()}

Notice the call above to next(). Calling this function invokes the next middleware function in the app.The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”.To avoid confusion, always use this convention.

To load the middleware function, call app.use(), specifying the middleware function.For example, the following code loads the myLogger middleware function before the route to the root path (/).

const express = require('express')const app = express()const myLogger = function (req, res, next) { console.log('LOGGED') next()}app.use(myLogger)app.get('/', (req, res) => { res.send('Hello World!')})app.listen(3000)

Every time the app receives a request, it prints the message “LOGGED” to the terminal.

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

If myLogger is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.

The middleware function myLogger simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.

Middleware function requestTime

Next, we’ll create a middleware function called “requestTime” and add a property called requestTimeto the request object.

const requestTime = function (req, res, next) { req.requestTime = Date.now() next()}

The app now uses the requestTime middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to req (the request object).

const express = require('express')const app = express()const requestTime = function (req, res, next) { req.requestTime = Date.now() next()}app.use(requestTime)app.get('/', (req, res) => { let responseText = 'Hello World!<br>' responseText += `<small>Requested at: ${req.requestTime}</small>` res.send(responseText)})app.listen(3000)

When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.

Middleware function validateCookies

Finally, we’ll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid.

Here’s an example function that validates cookies with an external async service.

async function cookieValidator (cookies) { try { await externallyValidateCookie(cookies.testCookie) } catch { throw new Error('Invalid cookies') }}

Here, we use the cookie-parser middleware to parse incoming cookies off the req object and pass them to our cookieValidator function. The validateCookies middleware returns a Promise that upon rejection will automatically trigger our error handler.

const express = require('express')const cookieParser = require('cookie-parser')const cookieValidator = require('./cookieValidator')const app = express()async function validateCookies (req, res, next) { await cookieValidator(req.cookies) next()}app.use(cookieParser())app.use(validateCookies)// error handlerapp.use((err, req, res, next) => { res.status(400).send(err.message)})app.listen(3000)

Note how next() is called after await cookieValidator(req.cookies). This ensures that if cookieValidator resolves, the next middleware in the stack will get called. If you pass anything to the next() function (except the string 'route' or 'router'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.

Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.

For more information about Express middleware, see: Using Express middleware.

Configurable middleware

If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.

File: my-middleware.js

module.exports = function (options) { return function (req, res, next) { // Implement the middleware function based on the options object next() }}

The middleware can now be used as shown below.

const mw = require('./my-middleware.js')app.use(mw({ option1: '1', option2: '2' }))

Refer to cookie-session and compression for examples of configurable middleware.

Writing middleware for use in Express apps (2024)
Top Articles
Does Bark Monitor Text Messages as Advertised? Review Bark's Capabilities
Faire un tour du monde sans argent
What Times What Equals 86
Experience
Truist Sat Hours
Google Alerts Login
Geheimtipp Anna Maria Island- die schönsten Strände Floridas | Reiseblog und Fotografieblog aus Österreich
Silnafil 25mg Tablet: View Uses, Side Effects, Price and Substitutes | 1mg
Project Zomboid Dynamic Skybox
Dom Tradingview
Aes Salt Lake City Showdown
Is Jackson On Jeopardy Transgender
Georgina Rodriguez Opium
Stigmata Of Sacrilege F95
Deluxeblondes Com
Discover Mia Malkova Bio/Wiki 2024 & Career Achievements – The Report
Chowrastha - Indian Eatery Nashua Reviews
Hindi Links 4U
Buzzr Tv Schedule Tonight
450 Miles Away From Me
Purdue Timeforge
Cooktopcove Com
H1889 007 04 - Local Ppo
Chelsea Galos on LinkedIn: #cannabisindustry #cannabisnews #newstoreopening #cannabisculture #newyork
South Bend Weather Underground
Otterbrook Goldens
Craigs List Corpus Christi
Jesus Calling January 8:Whenever you feel inadequate, Remember that I am your ever-present Help.-是是誰 D+ 看世界~*|痞客邦
Dan Pfeiffer Message Box
Vmgma Patient Portal
Pcc Skilled Nursing Login
Marina Mascarenhas (Nina) on LinkedIn: Changing jobs wasn’t originally in my 2024 plans, but I truly believe in… | 62 comments
Shiftselect Carolinas
Watermarke Tower Shooting
Artmusekitsmikash Rtic Divider/Cutting Board For 65 Gallon Rtic Coolers
Olivia Dunne says 'tears filled my eyes' as LSU won NCAA women's gymnastics championship
Inland Empire Personals Craigslist
Lesson 6 Becoming Familiar With Blueprint Systems Integration
Why Is 365 Market Troy Mi On My Bank Statement
Alineaciones De Rcd Espanyol Contra Celta De Vigo
Bustle Daily Horoscope
Ligue des champions 2024-2025 : calendrier, résultats, nouvelles règles
Riverside Urgent Care Meriden Ct
Aeries Birmingham Portal
Bolly2Tolly Maari 2
Vikram Vedha Download 2022
Hallmark White Coat Ceremony Cards
Www Publix Org Oasis Schedule
Streameast Io Soccer
Uhaul Service Tire Monitor System
First Mess Blog
Craigslist Metal Roofing
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 6106

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.