ajlind
ajlind

Reputation: 363

Node.js: is request unique?

In node.js, when using https-module and createserver. When user makes request to httpsserver, is request unique or can different request has same request (id?). If it is unique, which property should be to use?

Upvotes: 0

Views: 626

Answers (1)

jfriend00
jfriend00

Reputation: 708036

The request argument in an http request handler is a Javascript object and every one is unique. They are never reused. That object is documented here.

There is no such thing as a request ID in the node.js http library. If you want to make your own request ID, you can do that yourself by just assigning a symbol as a property of the request object. You can pick any property name to use that does not conflict with existing properties.

Since this is a bit of an unusual request, I'd ask you why you're trying to do this because there may be a better way to solve your problem than trying to make a request ID. If you show your actual code and what you're trying to do, we could probably help you more specifically.


If you were using Express, you could set your own request ID with some middleware like this:

// set request ID
let reqCntr = 0;
app.use((req, res, next) => {
    req._localID = reqCntr++;
    next();
});

Just place this middleware before any other request handlers that wish to use the id. You can pick any non-conflicting property name. I picked _localID.

Upvotes: 3

Related Questions