user994165
user994165

Reputation: 9512

Module scope in Node.js - Simultaneous Express requests

I'm using the id variable across different functions. The id is defined outside of the functions. Could this cause the variable to overwritten when receiving multiple simultaneous requests? Is the behavior the same when this is done in the browser instead of in Node.js?

var id;
server.get('/myapp', function (req, res, next) {
    id = uuid.v4();
}

Upvotes: 0

Views: 152

Answers (1)

jfriend00
jfriend00

Reputation: 708056

Yes, it causes conflicts

If your request handlers have any asynchronous operations in them which allow more than one request to be in flight at the same time, then YES, the use of a module level variable that more than one request may access will cause conflicts and one request could trounce the variable that another was using.

In a nutshell, don't do this

Module level variables are only for data that ALL requests can safely access and share. Data for a single request should be inside the request handler or a property on the request or response object or some similar-type object that is per-request and not shared among multiple requests.

Data needed only during the processing of a request

So, if you just need access to some data for the duration of this particular request, then you can put it in a local variable inside the request handler and you can pass it to any other functions you may call that need it while processing that request. Or, you can assign it as a property on the req object which is unique for each separate request and then pass the req object to any other functions you are calling that need access to the data.

Data needed from one request to the next, but different for each user

If you are trying to keep track of some data from one request to the next for one particular client, then you can't store it this way at all. You will likely need to use a session manager so you can create a lasting session that can be correlated with one particular browser from one request to the next. express-session is a popular session manager that makes it pretty easy.

The way a session manager works is that the first time a given browser hits your server, it is assigned a unique cookie. That cookie contains an encrypted session ID. Then, the session manager creates a session object that is indexed by that session ID. When a second request from the same browser comes in, then express-session gets that previously set cookie, decrypts the sessionID, looks up the corresponding session object and lets you then access any data you may have stored in the session object on behalf of this particular user.

Upvotes: 1

Related Questions