@webhandle/session-cookie
v1.0.0
Published
Uses JWT tokens to encrypt and store user/session information in cookies.
Readme
Uses JWT tokens to encrypt and store user/session information in cookies.
Standard node encryption infrastructure is used to encrypt and sign the information.
The normal caveats here will apply:
- Don't track a ton of information because it has to be sent on every single request which will kill performance.
- Don't track anything which can change elsewhere, like the groups a user is a member of. Doing so would cause supposedly authoritative information to be kept two places.
Install
npm i @webhandle/session-cookieConfigure
import setup from "@webhandle/session-cookie/initialize-webhandle-component.mjs"
setup(webhandle, options)If you'd like to set the life time of the cookie to something other than the default 30 days, the cookie name, or the attribute of the request object used for the token, you can configure with options like:
{
saveIdentity: true
, cookieName: 'persistent-information'
, requestAttribute: 'tracker'
, cookieMaxAge: 30 * 24 * 60 * 60 * 1000
, identity: {
// an identity as create by the Cryptographer in @webhandle/trust-me
}
}session-cookie will generate an identity if none is available in any of the
configuration options. If saveIdentity is true and webhandle has a configuration
file, that file will be updated with the created identity to be re-used next time.
This code still works if a new cryptographic identity is generated each time the server restarts, but any past user sessions will be invalidated.
Usage
// print the information in the tracker
webhandle.router.use((req, res, next) => {
console.log('tracking value: ' + JSON.stringify(req.tracker))
next()
})
// track the last page visited other than the home page
webhandle.router.get(/.+/, (req, res, next) => {
res.track({ path: req.path }, () => {
next()
})
})
// or
webhandle.router.get(/.+/, (req, res, next) => {
await res.track({ path: req.path })
next()
})
// delete the cookie and clear the cached information when the homepage is loaded
webhandle.router.get('/', (req, res, next) => {
res.track()
next()
})Any time you change the value you must await or get a callback so that the encryption can take place before the cookie is set.
