connect-redis is a Redis session store backed by node_redis, and is insanely fast :). Requires redis >= 2.0.0
for the SETEX command.
Yarn:
yarn add connect-redis express-session
npm:
npm install connect-redis express-session
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(
session({
store: new RedisStore(options),
secret: 'keyboard cat',
resave: false,
})
);
RedisStore
will generate a new Redis client (using node-redis
) given host
, port
or socket
options. You may also provide an existing client using the client
option. Existing clients must be compatible with the node-redis
API (e.g. ioredis
is a popular alternative).
Redis host (default: localhost
). Ignored when client
option used.
Redis port (default: 6379
). Ignored when client
option used.
Redis database (default: 0
). Ignored when client
option used.
Password for Redis authentication. Ignored when client
option used.
Redis socket. Ignored when client
option used.
Set true
to unref the Redis client, allowing Node to shutdown the process if Redis holding open the event loop.. Ignored when client
option used. Warning: this is an experimental feature.
Log Redis client errors to the console (default: true
). Ignored when client
option used.
If you need more explicit control you can provide a custom function instead:
var logFn = err => {
// Log client errors programmatically.
};
An instance of a node_redis
or node_redis
compatible client
Known compatible alternatives to node_redis
:
- ioredis
- redis-mock for testing.
Key prefix in Redis (default: sess:
)
Redis session TTL in seconds. (default: session.cookie.maxAge
if set or one day)
If you need more explicit control you can provide a custom function instead:
var ttlFn = (store, sess, sessionID) => {
// Calculate TTL programmatically.
return ttl;
};
Disables setting a TTL. This means keys will never expire and will stay in Redis until evicted by
other means (overrides ttl
option).
The encoder/decoder to use when storing and retrieving session data from Redis (default: JSON
).
interface Serializer {
parse(string): object;
stringify(object): string;
}
Value used for count parameter in Redis SCAN
command. Used for ids()
and all()
methods (default: 100
).
By default, the node_redis
client will auto-reconnect on lost connections. But requests may come in during that time. In Express, one way you can handle this scenario is including a "session check":
app.use(session(/* setup session here */));
app.use(function(req, res, next) {
if (!req.session) {
return next(new Error('oh no')); // handle error
}
next(); // otherwise continue
});
If you want to retry, here is another option.
MIT