-2

I have a scenario where I am trying to setup a session variable in one node.js file and then access that same session variable in another node.js.

I'm not sure if I have to require express twice, once in each node.js file.

Does anyone know how to set a session variable in one node.js file and then call a function in another node.js file to access the same session variable ?

Any suggestions would be much appreciated.

Ethan Richardson
  • 461
  • 2
  • 10
  • 28
  • There's so many ways you can share a value between two different modules. A session value as part of an Express server is usually shared between multiple route handlers or middleware handlers. We would need to see your code to give you an answer, as you're basically asking how Express and modules work. – james_womack Jul 26 '16 at 02:17

1 Answers1

1

A session variable usually only makes sense in the context of a request on behalf of a specific user (since the session belongs to a specific user).

So, if you in the middle of processing a request and you wish to use some functionality in another module and that other functionality wants access to the session state for the current request, then you would typically just pass the req object to the other module's method so that it can access the session associated with that request.

If, for some reason, you're not processing a request when you think you need access to the session info, then please explain more about what you're doing because you will have to have access to the user identifier that is the key into the session store in order to find the right session.


Remember, sessions are per-user and there can be zillions of them. You don't store them in a module variable. They live in the session store and are accessed via a user key (that is usually in a cookie).

So, a session only makes sense in the context of a specific user and usually that is within the context of a specific request that gives you straightforward access to the session. So, if you need to use a function in another module and that function needs access to the session, then just pass either the req object of the user session itself to the other method as an argument to the method call.


As always, we can answer much more specifically to your particular issue if you show us your actual code and show us the REAL problem you're trying to solve. General questions like this cause us to have to teach a wide general solution and we may or may not hit the exact mark of what you're trying to do and it takes us a lot more words than just showing you a few lines of your own code adapted to solve the problem.

jfriend00
  • 683,504
  • 96
  • 985
  • 979