This is a node Express middleware to store session into redis.
Install with:
$npm install node-redis-session
var express = require('express');
var cookieParser = require('cookie-parser');
var redisSession = require('node-redis-session');
var app = express();
app.use(cookieParser());
app.use(redisSession());
app.get('/', function(req, res) {
//just use req.session and it will be there,
//when next same browser request come.
if (!req.session.user) {
req.session.user = {name: 'anonymous'};
}
res.end('hello '+req.session.user.name);
});
app.listen(3000);
Session will be store in redis, as JSON.stringify(req.session). You can find it with redis command line.
Other way to establish a redisSession is:
var express = require('express');
var cookieParser = require('cookie-parser');
var redisSession = require('node-redis-session');
var app = express();
app.use(cookieParser());
app.use(redisSession({ cookieName: 'mySessionid' }));
So cookie-name in browser will be set as mySessionid
. It's useful when multi projects are use redisSession. Do this and escape projects from use same cookie-name.
redisOptions
: configure redis, must be a array. ex:[6379, 'localhost', {auth_pass: 'auth_pass'}]
redisClient
: redis client, if exists ignore redisOptions.cookieName
: overwrite default cookie name, useful in multi products.expireTime
: cookie expire time in browser / session expire time in redis. count with ms.cacheCookieName
: multi application use sso will hold same session. and use this to hold a cache in single app. usage:req.cache
.cookieOptions
: see third param in http://expressjs.com/zh-cn/api.html (search res.cookie). // Object.assign({expires, httpOnly}, cookieOptions);
$npm test