Search code examples
node.jscookie-session

How is 'req.session' change detected in cookie-session middleware?


From the Readme.md file, it says,

The middleware will automatically add a Set-Cookie header to the response if the contents of req.session were altered.

Where is the implementation of detecting req.session change? Could you point me to the code or explain me how is this change detected?


Solution

  • With an Object.defineProperty on https://github.com/expressjs/cookie-session/blob/3dba6fb1287b19ee2f0cb3edb8a0f2afcf65bb7f/index.js#L74:

        Object.defineProperty(req, 'session', {
          configurable: true,
          enumerable: true,
          get: getSession,
          set: setSession <---- this one
        })
    

    setSession is called when the propriety is assigned, and setSession will set the cookie