DEV Community

loading...
Cover image for Custom Middleware Function in Express

Custom Middleware Function in Express

dmarcr1997 profile image Damon Marc Rocha II ・2 min read

So this last week I learned how to created custom middleware functions when using Express. Middleware functions are run before the main routes and can be executed on every route call or conversely when calling specific routes.

Middleware functions in Express are used to accomplish four things:

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

Express has a vast amount of middleware functions available for use, but if you cannot find one that fits your needs it is sooo easy to make your own. Before that, however, I want to briefly cover how to use middleware functions in Express.

So How Do I Use Middleware

There are three simple ways to use middleware in express:

app.use(cors())
Enter fullscreen mode Exit fullscreen mode
app.get('/', cors(), (req,res) =>{..Controller Function..})
Enter fullscreen mode Exit fullscreen mode
app.post('/',[cors(), json, morgan('dev')], (req,res) => {..Controller Function..})
Enter fullscreen mode Exit fullscreen mode

So to explain the three examples I gave above; app.use allows the middleware function passed in to be run before every request, the next example uses middleware as the second argument in a route call and then calls the function before the controller in the route. The last example passes a list of middleware functions to be run before the controller. For more information on how to use middleware, you can go to the Express middleware page.

Getting to the Point

So now you know how to use middleware and want to implement your own. Well, the good news is there is only one thing to learn, the next function. Middleware functions take in three arguments the request, response, and next. The request and response are the same as what you would use in routes, so I am not going to cover that here. However, the next parameter is extremely important, if you do not want your request to time out. At the end of your middleware function, you must call next() otherwise the server will never leave your function. To show this I built a simple middleware function that logs the data to be passed into a post route.

const logData = (req,res, next) => {
      console.log(`Data: ${req.body}`)
      next() 
}
app.post('/data', logData, (req,res) => {
    res.send({message: 'Got the data'})
})
Enter fullscreen mode Exit fullscreen mode

Notice anything, familiar. The middleware function is nothing special, it is literally a javascript function that can be anything you want as long as it ends in next() and is either set up to be called by express using app.use or in a route as shown above.
So go create some awesome middleware. I would love to see the things you guys can create with this.

Discussion

pic
Editor guide