Published on

Expressjs Middleware


We are using ExpressJS to expose the REST API for a project we are working on. It really is an awesome piece of software, it is very versatile yet still easy to use which is no small feat.

This is demonstrated very clearly when writing middleware for Express. Middleware is essentially a piece of code you want to run before one or more routes. To define the middleware you simply implement a function with the following signature:

function myHandler(/*error,*/ request, response, next) {
  //you can include an additional first parameter if you want your handler to handle errors

  request.someVariable = foo
  request.someOtherVariable = bar
  if (someCondition) {
    //we have an error so return...
    return response.status(500).send('Invalid parameters!')

In the above someVariable is accessible in routers by accessing them off of the request object in those routers. For example:

expressInstance.get('/blah', (request, response) => {
  const { someVariable, someOtherVariable } = request
  // use someVariable and someOtherVariable as needed
  // if the error condition someCondition was met in myHandler this router will not even be hit and instead the error from the handler will be returned

To use the handler you can make all routers use it as follows:


Alternatively you can use these only on routes that need them as below:

expressInstance.get('/foo', (request, response) => {
  //myHandler will not be called here
expressInstance.get('/blah', myHandler, (request, response) => {
  //myHandler will be called here

More detail on writing ExpressJS middleware can be found here.