If Javascript copies objects by reference, then does Express clone the req
and res
objects before passing them down to each request handler? If not, then how does Express handle possible conflicts between routes running simultaneously and using the same reference to req
and res
?

- 1,489
- 2
- 17
- 27
3 Answers
Express doesn't clone req
and res
. You can see that in this example app:
var http = require('http');
var express = require('express');
var app = express();
var testReq, testRes;
app.use(function(req, res, next) {
console.log('middleware');
testReq = req;
testRes = res;
next();
});
app.get("*", function(req,res) {
console.log('route')
console.log('req the same? ' + (req === testReq)); // logs true
console.log('res the same? ' + (res === testRes)); // logs true
res.send(200);
});
http.createServer(app).listen(8080);
Test with curl
:
$ curl localhost:8080
This is a useful feature - it means that middleware functions can use req
and res
to pass data to downstream functions. For example an authorisation middleware might add a req.user
property.
Concurrency isn't a concern here because Node.js is single threaded - it is not possible for two routes to run at any given time.
It also doesn't run a single request through multiple routes - you can add another get("*")
route and you'll see that it won't get called.

- 29,767
- 10
- 79
- 91
-
So, does that mean that routes in node/express are blocking? Will an expensive computation in route A block the execution of routes B, C and D, should a new request come to them? – miniml Oct 12 '15 at 18:47
-
No, all I/O in Node is non-blocking by default. That's why so many functions take callbacks - they are invoked asynchronously when the operation has finished. – joews Oct 12 '15 at 18:51
-
I missed the part about expensive computation - yes, CPU-bound code can block. It's good practice to split slow computations across call stacks. You can do that with [`setImmediate` or `process.nextTick`](http://stackoverflow.com/questions/15349733/setimmediate-vs-nexttick) or a helper library like `async`. – joews Oct 12 '15 at 18:56
-
Or better yet, reverse proxy into multiple instances of the same server. – Amit Oct 12 '15 at 22:40
-
Reverse proxying is great for load balancing but you should still avoid blocking the event loop in a single Node process. – joews Oct 12 '15 at 22:46
As JavaScript is single threaded, there is no simultaneous route handling and no multithreading pitfalls exist. req
& res
are not cloned, they are extended.

- 45,440
- 9
- 78
- 110
When we say parallel requests, it means the client is creating a connection stream and gives it in the form of request
or whatever you name it as.
A sequence of middleware will get it sequentially one after the other, based on the call to next
, while getting appended with necessary things from middleware.
But the router.all/*('path', [middleware])
triggers for each request made by the clients.

- 1,695
- 12
- 23