user3018765
user3018765

Reputation: 67

Difference between req.session and req.app and app.set in express

What us the difference between req.session vs req.app vs app.set in Express app. Say I have redis session store. Are they all saved in a session store, or memory.

Upvotes: 0

Views: 636

Answers (2)

jfriend00
jfriend00

Reputation: 707916

req.app is a reference to the Express app object that was associated with the route handler that is handling the current request. This allows you to more easily get to that app object, particularly if routes are defined in separate modules.

So, if you did something like this:

app.get('/viewdirectory', require('./mymiddleware.js'))

Then, that middleware would be able to reach the app object via req.app during a request where it otherwise wouldn't have that ability without manually passing the app object in a less convenient module constructor.

app.set() is an ability to set various configuration options on the app object. Those options are documented here.

req.session is a session object used by some session middleware. Express does not come pre-configured with built-in session management. There are many different session add-ons for Express. Some of them use middleware that places the session in req.session so you can easily access it in any request handler. Putting the session reference in req.session is a common convention to make it easy for request handlers to get to when servicing a request.

Where the session is actually stored for the longer duration outside of a request depends upon the particular session implementation. Some session are just stored in JS objects in memory. Some are stored in a shared in-memory database like redis. Some are stored in a regular, file-based database. Some session implementations allow you to pick which type of session storage you want to use.

Upvotes: 0

razakj
razakj

Reputation: 1049

Express doesn't have session handling implementation in its core. You have to use session middleware which is then used to handle the sessions. (it's installed automatically via express-generator)

If you have a look at the documentation of the session module you'll see that it can use different types of storage to store your session data. Memory is used by default and should only be used for your development purpose due to as-designed memory leak. For production you can use store of your choice such as connect-redis, connect-mysql and many others.

To answer your questions :

  • The middleware then exposes req.session which you can use to access session data.
  • req.app is a reference to express application instance and has nothing to do with sessions.
  • app.set is used to set application level locals and has nothing to do with sessions.
  • When you use RedisStore then your session data are stored in Redis database.

Upvotes: 2

Related Questions