0

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();
});
0

2 Answers 2

3

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"

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.