express-session full featured
MemoryStoremodule without leaks!
A session store implementation for Express using lru-cache.
The default MemoryStore from express-session can leak memory because it does not provide a suitable way to expire sessions.
The sessions are still stored in memory, so they're not shared with other processes or services.
$ npm install express-session memorystore
Pass the express-session store into memorystore to create a MemoryStore constructor.
const session = require('express-session')
const MemoryStore = require('memorystore')(session)
app.use(session({
cookie: { maxAge: 86400000 },
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
resave: false,
secret: 'keyboard cat'
}))checkPeriodDefines how oftenMemoryStorechecks for expired entries. The period is in ms. The automatic check is disabled by default. Not setting this is kind of silly, since that's the whole purpose of this library.maxThe maximum size of the cache, checked by applying the length function to all values in the cache. It defaults toInfinity.ttlSession TTL (expiration) in milliseconds. Defaults tosession.cookie.maxAge(if set), or one day. This may also be set to a function of the form(options, sess, sessionID) => number.disposeFunction that is called on sessions when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when sessions are no longer accessible. Called withkey, value. It's called before actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in anextTickorsetTimeoutcallback or it won't do anything.staleBy default, if you set amaxAge, it'll only actually pull stale items out of the cache when youget(key). (That is, it's not pre-emptively doing asetTimeoutor anything.) If you setstale:true, it'll return the stale value before deleting it. If you don't set this, then it'll returnundefinedwhen you try to get a stale entry, as if it had already been deleted.noDisposeOnSetBy default, if you set adispose()method, then it'll be called whenever aset()operation overwrites an existing key. If you set this option,dispose()will only be called when a key falls out of the cache, not when it is overwritten.serializerAn object containingstringifyandparsemethods compatible with JavaScript'sJSONto override the serializer used.
memorystore implements all the required, recommended and optional methods of the express-session store. Plus a few more:
-
startInterval()andstopInterval()methods to start or clear the automatic expired-session check. -
prune()that you can use to manually remove only the expired entries from the store.
To enable debug logging, set the env var DEBUG=memorystore.
Rocco Musolino (@roccomuso)
MIT