Search code examples
node.jsexpressvariablescookiesreq

Where is req.variable stored?


Similar question (but NOT a duplicate): How do i store request-level variables in node.js?

Consider this following code:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
   req.someVariable = "Hello";
   res.send(req.someVariable + ' world!');
});

Where is req.someVariable stored? In a cookie? Does this apply for the user only or everyone? Also, what's the difference between these and storing them in sessions/cookies?


Solution

  • In addition to req being just a javascript object variable, stored in memory, do note express has a res.locals object variable that persist through the request/response cycle.

    If you want to store any user information, you should be using the res.locals object so you do not accidentally overwrite other important objects.

    res.locals

    An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals. This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

    http://expressjs.com/en/5x/api.html#res.locals

    app.use(function (req, res, next) {
      res.locals.user = req.user
      res.locals.authenticated = !req.user.anonymous
      next()
    })
    

    Note: res.locals on it's own is not sent together with the response (e.g. res.send). It's only accessible in your nodejs app.

    Cookies

    Cookies are information bits that you want to send to the client's browser (stored in browser memory). The client can then send the cookie back to your nodejs app. These are different from req and res properties.

    Cookie can store for example, an authentication token, which can be stored in the client's browser, and provided to the nodejs app on every request.

    For security, you can use a httpOnly cookie which cannot be modified by browser javascript.