Express.Js Middleware, What is next()?

You may have noticed use of next() function while looking at node.js code.

Express is a routing web framework which utilize essentially a series of middleware calls. piece of code for a simple route could be like bellow.

and with a additional parameter next

So what is next() doing here. In the example, for instance, you might look up the user in the database against provided user_id but if user not found in database, It passes control to the next matching route. It is a more flexible and powerful tool that could sit between/before the routes and can perform specific tasks for you.

Let say you want to perform check if user is authenticated  and have a started session with app, It is much easy to deal with that using middleware instead of specifically check at each route.

It will check session before each route as long as we put this code before our routes. Express will run middleware in the order added to the stack. The router is one of these middleware functions. As long as you get your above function into the stack before the router, it will be used by all routes and things will work.

There is list of common actions you can perform using middleware. such as logger, bodyParser, cookieParser, errorHandler etc.