feat: add support to dynamic cookie options by lincond · Pull Request #1027 · expressjs/session
This patch introduces support for dynamic cookie generation in express-session. Instead of only accepting a static object for the options.cookie parameter, the patch allows developers to supply a function that returns a cookie options object. This enables dynamic generation of cookie settings on a per-request basis.
Changes Made:
- JSDoc Update:
The type for options.cookie has been updated from Object to Object|Function to reflect the new functionality
- Dynamic Cookie Options Resolution:
In the session middleware, when generating a new session, the code now checks if cookieOptions is a function. If it is, it calls the function with the current request (req) as an argument to retrieve the cookie options. Otherwise, it uses the static options as before.
req.session.cookie = new Cookie( typeof cookieOptions === 'function' ? cookieOptions(req) : cookieOptions );
- Path Mismatch Check:
The cookie path validation now also resolves the cookie options dynamically to ensure that the generated cookie options are used in the check.
var resolvedCookieOptions = typeof cookieOptions === 'function' ? cookieOptions(req) : cookieOptions; if (originalPath.indexOf(resolvedCookieOptions.path || '/') !== 0) { // Handle pathname mismatch debug('pathname mismatch'); next(); return; }
Motivation and Use Case:
This change was made to address scenarios where the cookie configuration (e.g., the cookie path) needs to be determined dynamically based on the incoming request. For example, in multi-tenant applications where different URL paths should result in different cookie configurations, this enhancement allows the session middleware to generate the correct cookie settings on the fly.
Testing:
To test this change, you can set the options.cookie to a function that returns a cookie options object based on the request. Verify that:
- When a function is provided, it correctly generates the cookie settings for each request.
- When a static object is provided, the behavior remains unchanged.
Feel free to provide any feedback or suggestions for further improvements.