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

Try it out

There’s a also working example on codesandbox – feel free to test it out if enough credits are available.

Happy coding 🙂

Useful links