Express: middleware function with custom parameters

Implementing an Express middleware function that can handle custom parameters.

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

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'
    // ...

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.

Try it out

See a working example on codesandbox…

Happy coding 🙂

Useful links