ExpressJS Middleware req, res, next scope

express, node.js

Solution

Remember functions are objects in JS, so they can be passed around and returned like any other object.

When you tell express to use your middleware, you are calling the `myMiddleWare` function:

app.use(myMiddleWare());

this call returns the anon function you labelled as `\\2.`. Express.js will then call it as part of it's middleware stack when processing a request, giving it the `req`, `res` and `next` arguments.

You can always see which arguments are passed to a function by inspecting the `arguments` object. (i.e. `console.log(arguments)`);

Problem

After studying some Middlewares I have still a question. Have a look at the following working setup, It just attaches the do it function to the req object so that we can call it in any route just like `req.doit()` But where does the req, res, next come from?, I never passed them and I am even more curious how it works since the anonymous function (2.) is surrounded by another function (1.) which I even can pass arguments. MiddleWareTest.js: ``` var test = function(options){ //1.) return function(req, res, next) { //2.) req.doit = function() { console.log('doit') } next(); } } module.exports = test; ``` app.js: ``` ... var myMiddleware = require('./MiddlewareTest.js') app.use(myMiddleware()) ... ``` Any suggestions to deepen my knowledge are welcome.

Original source