middleware function with custom parameters – tsmx (2024)

by tsmx-dev

Implementing an Express middleware function that can handle custom parameters.

Table of Contents

Express middleware functions – a quick intro

With Express you can easily write your own middleware functions. In short terms, a middleware function is a piece of logic executed in between receiving a request and sending the response.

A standard middleware function always follows a signature with the three arguments (req, res, next) where req is the incoming request, res the response to be sent and next a reference to a function for stepping to the next middleware function.

Here’s an example of a standard middleware function and its usage in a get route.

const myMiddleware = (req, res, next) => { // do some logic with req, res // ... // advance to the next processing step next();}app.get('/', myMiddleware, (req, res) => { res.send('...'); });

For more details have a look at the comprehensive Express middleware guide.

Upgrading to parameterized middleware function

So far, so good. But what if you need other input parameters for you business logic deviating from (req, res, next)? For example, if you want to hand over some configuration values to feed your logic?

To achieve this, you can use a simple but efficient pattern: wrap your actual middleware function with a second one that receives the desired parameters, like so.

const paramMiddleware = (myParam) => { return (req, res, next) => { // implement your business logic using 'myParam' // ... next(); }}

Then, simply pass the desired parameter to the middleware wrapper function when passing to the Express routes.

app.get('/', paramMiddleware('param'), (req, res) => { res.send('...'); });

Of course this works with 1..n parameters.

A minimal working example

Putting it all together, here’s a minimal complete example of an Express middleware function that takes a custom parameter.

var express = require('express');var app = express();const setRequestInfo = (text) => { return (req, res, next) => { req.requestInfo = text; next(); };};app.get('/', setRequestInfo('Test-123'), (req, res) => { res.send('Hi there! requestInfo = ' + req.requestInfo);});app.listen(3000);

Note: As shown in the example it is very usual to store results of a middleware function needed later on in your business logic in newly created attributes of the req object. Please ensure that you are using unique attribute names for that and don’t override any existing attribute already used by Express or other middleware functions.

Happy coding 🙂

Useful links

middleware function with custom parameters – tsmx (2024)
Top Articles
Positive action or positive discrimination
What is Estate Planning?
Bubble Guppies Who's Gonna Play The Big Bad Wolf Dailymotion
55Th And Kedzie Elite Staffing
Farepay Login
Driving Directions To Fedex
Google Jobs Denver
15 Types of Pancake Recipes from Across the Globe | EUROSPAR NI
Craigslist - Pets for Sale or Adoption in Zeeland, MI
Day Octopus | Hawaii Marine Life
Shariraye Update
W303 Tarkov
iLuv Aud Click: Tragbarer Wi-Fi-Lautsprecher für Amazons Alexa - Portable Echo Alternative
Patrick Bateman Notebook
Kürtçe Doğum Günü Sözleri
Daylight Matt And Kim Lyrics
10 Fun Things to Do in Elk Grove, CA | Explore Elk Grove
Gina Wilson All Things Algebra Unit 2 Homework 8
The Tower and Major Arcana Tarot Combinations: What They Mean - Eclectic Witchcraft
Zillow Group Stock Price | ZG Stock Quote, News, and History | Markets Insider
The Listings Project New York
Walgreens 8 Mile Dequindre
Rapv Springfield Ma
Cardaras Funeral Homes
Mta Bus Forums
Bj타리
Rgb Bird Flop
Our Leadership
R/Mp5
Advance Auto Parts Stock Price | AAP Stock Quote, News, and History | Markets Insider
Six Flags Employee Pay Stubs
1987 Monte Carlo Ss For Sale Craigslist
Xemu Vs Cxbx
Montrose Colorado Sheriff's Department
Deshuesadero El Pulpo
Gary Lezak Annual Salary
T&Cs | Hollywood Bowl
Ferguson Showroom West Chester Pa
Setx Sports
Citroen | Skąd pobrać program do lexia diagbox?
2Nd Corinthians 5 Nlt
Uc Davis Tech Management Minor
Collision Masters Fairbanks
20 Mr. Miyagi Inspirational Quotes For Wisdom
The Bold and the Beautiful
El Patron Menu Bardstown Ky
St Als Elm Clinic
A Snowy Day In Oakland Showtimes Near Maya Pittsburg Cinemas
O'reilly's Eastman Georgia
Taterz Salad
Itsleaa
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5701

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.