Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript
What steps should I take to lawfully visit the United States as a tourist immediately after visiting on a B-1 visa?
Would dual wielding daggers be a viable choice for a covert bodyguard?
For a hashing function like MD5, how similar can two plaintext strings be and still generate the same hash?
Using Newton's shell theorem to accelerate a spaceship
Why doesn't sea level show seasonality?
What prevents someone from claiming to be the murderer in order to get the real murderer off?
Has anyone in space seen or photographed a simple laser pointer from Earth?
What does (void *)1 mean
Why does the U.S. tolerate foreign influence from Saudi Arabia and Israel on its domestic policies while not tolerating that from China or Russia?
Modulus Operandi
What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?
How to ask for a LinkedIn endorsement?
Good resources for solving techniques (Metaheuristics, MILP, CP etc)
How would vampires avoid contracting diseases?
Is "I do not want you to go nowhere" a case of "DOUBLE-NEGATIVES" as claimed by Grammarly?
Single word for "refusing to move to next activity unless present one is completed."
Print the last, middle and first character of your code
How do you glue a text to a point?
Are randomly-generated passwords starting with "a" less secure?
Is a 10th-level Transmutation wizard considered a shapechanger for the purpose of effects such as Moonbeam?
Why isn't pressure filtration popular compared to vacuum filtration?
Keep milk (or milk alternative) for a day without a fridge
How to evolve human-like eyes that can stare at the sun without protection?
How is angular momentum conserved for the orbiting body if the centripetal force disappears?
Access current req object everywhere in Node.js Express
Why are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I wonder how to access req object if there's no 'req' parameter in callback.
This is the scenario:
In ExpressJs, I have a common function, it uses to handle something with 'req' object, but not pass req into it.
module.exports =
get: function()
var req = global.currentRequest;
//do something...
My current solution is that I write a middleware for all request, I put the 'req' in global variable, then I can access the 'req' everywhere with 'global.currentRequest'.
// in app.js
app.use(function (req, res, next)
global.currentRequest= req;
next();
);
But I don't know if it's good? Can anyone have suggestions?
Thanks a lot!
node.js express
add a comment |
I wonder how to access req object if there's no 'req' parameter in callback.
This is the scenario:
In ExpressJs, I have a common function, it uses to handle something with 'req' object, but not pass req into it.
module.exports =
get: function()
var req = global.currentRequest;
//do something...
My current solution is that I write a middleware for all request, I put the 'req' in global variable, then I can access the 'req' everywhere with 'global.currentRequest'.
// in app.js
app.use(function (req, res, next)
global.currentRequest= req;
next();
);
But I don't know if it's good? Can anyone have suggestions?
Thanks a lot!
node.js express
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
The only proper way is to pass thereq
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
– jfriend00
Sep 6 '16 at 4:07
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48
add a comment |
I wonder how to access req object if there's no 'req' parameter in callback.
This is the scenario:
In ExpressJs, I have a common function, it uses to handle something with 'req' object, but not pass req into it.
module.exports =
get: function()
var req = global.currentRequest;
//do something...
My current solution is that I write a middleware for all request, I put the 'req' in global variable, then I can access the 'req' everywhere with 'global.currentRequest'.
// in app.js
app.use(function (req, res, next)
global.currentRequest= req;
next();
);
But I don't know if it's good? Can anyone have suggestions?
Thanks a lot!
node.js express
I wonder how to access req object if there's no 'req' parameter in callback.
This is the scenario:
In ExpressJs, I have a common function, it uses to handle something with 'req' object, but not pass req into it.
module.exports =
get: function()
var req = global.currentRequest;
//do something...
My current solution is that I write a middleware for all request, I put the 'req' in global variable, then I can access the 'req' everywhere with 'global.currentRequest'.
// in app.js
app.use(function (req, res, next)
global.currentRequest= req;
next();
);
But I don't know if it's good? Can anyone have suggestions?
Thanks a lot!
node.js express
node.js express
asked Sep 6 '16 at 2:05
SkySky
311 silver badge4 bronze badges
311 silver badge4 bronze badges
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
The only proper way is to pass thereq
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
– jfriend00
Sep 6 '16 at 4:07
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48
add a comment |
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
The only proper way is to pass thereq
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
– jfriend00
Sep 6 '16 at 4:07
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
The only proper way is to pass the
req
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.– jfriend00
Sep 6 '16 at 4:07
The only proper way is to pass the
req
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.– jfriend00
Sep 6 '16 at 4:07
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48
add a comment |
3 Answers
3
active
oldest
votes
The only proper way is to pass the req
object through as an argument to all functions that need it.
Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.
There is no shortcut here. You will just have to pass the req
object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.
There are some circumstances where you may be able to use a closure to "capture" the desired req
object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.
add a comment |
Instead of going with globals, which is never the best idea,
you can wrap module.exports
to accept req
as a param.
module.exports = function (req)
function get()
// it has access to req.
console.log(req);
return get;
And you can require
the above module as
app.use(function (req, res, next)
const mod = require('/path/to/module')(req);
next();
);
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express ontoreq
are unique.
– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
add a comment |
Actually, this is possible with something like global-request-context
This is using zone.js which let you persist variables across async tasks.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39339640%2faccess-current-req-object-everywhere-in-node-js-express%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
The only proper way is to pass the req
object through as an argument to all functions that need it.
Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.
There is no shortcut here. You will just have to pass the req
object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.
There are some circumstances where you may be able to use a closure to "capture" the desired req
object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.
add a comment |
The only proper way is to pass the req
object through as an argument to all functions that need it.
Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.
There is no shortcut here. You will just have to pass the req
object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.
There are some circumstances where you may be able to use a closure to "capture" the desired req
object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.
add a comment |
The only proper way is to pass the req
object through as an argument to all functions that need it.
Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.
There is no shortcut here. You will just have to pass the req
object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.
There are some circumstances where you may be able to use a closure to "capture" the desired req
object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.
The only proper way is to pass the req
object through as an argument to all functions that need it.
Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.
You cannot put request-specific data into a global in node.js, ever. Doing so will create an opportunity for two requests that are in-flight at the same time to stomp on each other and for data to get confused between requests. Remember, this is a server that is potentially handling requests for many clients. You cannot use synchronous, one-at-a-time thinking for a server. A node.js server may potentially have many requests all in flight at the same time and thus plain globals cannot be used for request-specific data.
There is no shortcut here. You will just have to pass the req
object through to the function that needs it. If that means you have to change the function signature of several intervening functions, then so-be-it. That's what you have to do. That is the only correct way to solve this type of problem.
There are some circumstances where you may be able to use a closure to "capture" the desired req
object and then use it in inner functions without passing it to those inner functions, but it does not sound like that is your function structure. We'd have to see a lot more of your real/actual code to be able to know whether that's a possibility or not.
answered Sep 8 '16 at 5:19
jfriend00jfriend00
455k59 gold badges611 silver badges649 bronze badges
455k59 gold badges611 silver badges649 bronze badges
add a comment |
add a comment |
Instead of going with globals, which is never the best idea,
you can wrap module.exports
to accept req
as a param.
module.exports = function (req)
function get()
// it has access to req.
console.log(req);
return get;
And you can require
the above module as
app.use(function (req, res, next)
const mod = require('/path/to/module')(req);
next();
);
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express ontoreq
are unique.
– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
add a comment |
Instead of going with globals, which is never the best idea,
you can wrap module.exports
to accept req
as a param.
module.exports = function (req)
function get()
// it has access to req.
console.log(req);
return get;
And you can require
the above module as
app.use(function (req, res, next)
const mod = require('/path/to/module')(req);
next();
);
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express ontoreq
are unique.
– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
add a comment |
Instead of going with globals, which is never the best idea,
you can wrap module.exports
to accept req
as a param.
module.exports = function (req)
function get()
// it has access to req.
console.log(req);
return get;
And you can require
the above module as
app.use(function (req, res, next)
const mod = require('/path/to/module')(req);
next();
);
Instead of going with globals, which is never the best idea,
you can wrap module.exports
to accept req
as a param.
module.exports = function (req)
function get()
// it has access to req.
console.log(req);
return get;
And you can require
the above module as
app.use(function (req, res, next)
const mod = require('/path/to/module')(req);
next();
);
answered Sep 6 '16 at 3:33
Swaraj GiriSwaraj Giri
3,1172 gold badges17 silver badges31 bronze badges
3,1172 gold badges17 silver badges31 bronze badges
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express ontoreq
are unique.
– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
add a comment |
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express ontoreq
are unique.
– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
The problem is just I cannot pass req as a param into that func, because the func has been called too much, then I have to modify all callers.
– Sky
Sep 6 '16 at 3:59
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express onto
req
are unique.– Swaraj Giri
Sep 6 '16 at 15:44
@Sky What do you mean by "the func has been called too much, then I have to modify all callers"? All http requests that are eventually passed by express onto
req
are unique.– Swaraj Giri
Sep 6 '16 at 15:44
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
I don't understand how this could work? Could you extend to give an example use?
– John
Nov 14 '17 at 12:21
add a comment |
Actually, this is possible with something like global-request-context
This is using zone.js which let you persist variables across async tasks.
add a comment |
Actually, this is possible with something like global-request-context
This is using zone.js which let you persist variables across async tasks.
add a comment |
Actually, this is possible with something like global-request-context
This is using zone.js which let you persist variables across async tasks.
Actually, this is possible with something like global-request-context
This is using zone.js which let you persist variables across async tasks.
answered Mar 26 at 2:04
Tom EsterezTom Esterez
15.4k7 gold badges26 silver badges33 bronze badges
15.4k7 gold badges26 silver badges33 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39339640%2faccess-current-req-object-everywhere-in-node-js-express%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Avoid using global variables unless you are really left without a choice. It is considered to be an anti-pattern. See: stackoverflow.com/questions/18635136/…
– Samuel Toh
Sep 6 '16 at 3:40
The only proper way is to pass the
req
through as an argument to all functions that need it. Stashing it in a global simply will not work because multiple requests can be in process at the same time if any requests use async calls as part of their processing and those multiple requests will stomp on each other making a hard to track down bug. There are no shortcuts here. Pass the current request as an argument to any code that needs it.– jfriend00
Sep 6 '16 at 4:07
like jfriend00 wrote it's a really bad idea. Also, it was discussed hundreds of time on stack and you will not find a proper solution. The problem is that you try to apply sync thinking for async programming. Often in movie Kungfu master says that you have to change your way of thinking.
– Boris Siscanu
Sep 6 '16 at 6:48