Alexander Mills
Alexander Mills

Reputation: 99970

Node.js Express app - request object

Why does the request object usually denoted as "req", remain the same throughout the application lifecycle? You can see this variable in callbacks with signatures like function(req,res,next) If I attach a variable to that req object, like req.user, then that user object seems to exist throughout the application, is that true and if so why?

Is this true only of app.use like so?

app.use(function (request, response, next) {
    request.user= user;
    next();
});

Upvotes: 0

Views: 1105

Answers (2)

Yogesh Khatri
Yogesh Khatri

Reputation: 1210

request object will be same throughtout the request lifecycle and not application lifecycle.
e.g. you have a route like this, with two middlewares (can be of any number)

app.get("/profile", authenticate, UserController.profile);

Now whenever there is a request on path /profile express will call two functions authenticate and UserController.profile in order.
And will pass three arguments to each function req, res, next.
But how will express know if first function has completed its execution? it knows using next callback. So when authenticate will call next() express knows the functions execution is completed and will call UserController.profile with same arguments.

As req is an object and every callback is passed the same req object, so any change you make in the object will be available to every middleware/callback express calls for that particular request.

Is this true only of app.use like so?

No, it is true for routes methods too. Route methods are called only when the route matches, while app.use middlewares are called for each request.

Upvotes: 2

Andrey Sidorov
Andrey Sidorov

Reputation: 25446

It's not the same "throughout the application lifecycle", it's the same throughout middleware stack. Express is based on Connect, and connect brings the notion of "middleware stack" - you register functions that do something with request/response and able to pass (or not) work up to the next layer in the middleware. All functions in the "stack" operate on the same request/response, but each new request result in new instance of request/response objects.

Basically, the answer is "it's because Connect is designed to work this way"

Upvotes: 3

Related Questions