connect-redis is a Redis session store backed by node_redis, and is insanely fast :). Requires redis >= 2.0.0
for the SETEX command.
$ npm install connect-redis
In order to use the latest connect-redis
you also have to use express-session
instead of the default connect session
middleware.
$ npm install express-session
Then follow the usage instructions below.
A Redis client is required. An existing client can be passed directly using the client
param or created for you using the host
, port
, or socket
params.
client
An existing client created usingredis.createClient()
host
Redis server hostnameport
Redis server portnosocket
Redis server unix_socket
The following additional params may be included:
ttl
Redis session TTL (expiration) in secondsdisableTTL
disables setting TTL, keys will stay in redis until evicted by other means (overidesttl
)db
Database index to usepass
Password for Redis authenticationprefix
Key prefix defaulting to "sess:"unref
Settrue
to unref the Redis client. Warning: this is an experimental feature.
Any options not included in this list will be passed to the redis createClient()
method directly.
Pass the express-session
store into connect-redis
to create a RedisStore
constructor.
var express = require("express");
var session = require("express-session");
var RedisStore = require("express-django-redis-session")(session);
var middleware = require("express-django-redis-session/middleware");
var app = express();
var sidName = "sessionid";
var secret = "secret";
var cookieName = "sess";
var cookieOptions = {
path: '/',
httpOnly: true,
secure: false,
maxAge: null,
domain: '.example.com'
}
app.use(middleware({
sidName: sidName,
secret: secret,
cookieName: cookieName,
cookie: cookieOptions
}));
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 0,
prefix: 'session:'
}),
secret: secret,
resave: false,
saveUninitialized: false,
name: cookieName,
cookie: cookieOptions
}));
Since node_redis
which this library wraps does not include the ability to create a client from a URL. Neither does this library. However, there's a separate module that can be used in conjunction to get this behavior.
By default, the node_redis
client will auto-reconnect when a connection is lost. But requests may come in during that time. In express, one way this scenario can be handled is including a "session check" after setting up a session (checking for the existence of req.session
):
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