Book Image

Web Development with MongoDB and Node.js

By : Jason Krol
Book Image

Web Development with MongoDB and Node.js

By: Jason Krol

Overview of this book

Table of Contents (19 chapters)
Web Development with MongoDB and Node.js
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
12
Popular Node.js Web Frameworks
Index

Custom middleware


There will undoubtedly come a time when you want to write your own custom middleware in addition to the existing middleware provided by Connect or any other third party. Before you write your own custom anything in Node, make it a habit to search through https://www.npmjs.org/ first, as there's a fairly big chance someone else has already done the work.

Writing your own custom middleware is pretty simple. You simply need to write a function that accepts four parameters: err, req, res, and next. The first parameter is an error object, and if there were any stack errors prior to your middleware running, that error will be passed to your middleware so you can handle accordingly. You are already familiar with the req and res parameters having written your routes. The fourth parameter is actually a reference to a callback. This next parameter is how the middleware stack is able to behave like a stack—each executing and ensuring that the next middleware in the pipeline is returned...