StevenZ
StevenZ

Reputation: 141

redis to save session and other data

How to use redis to store session and other data?

I got error "myRedis Error-> Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED". Without the myRedis part, the express/session/redis runs fine.

var express = require('express');
var session = require('express-session');

// pass the express to the connect redis module
// allowing it to inherit from session.Store
var RedisStore = require('connect-redis')(session);

....
// Populates req.session
app.use(session({
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  secret: 'keyboard cat',
  store: new RedisStore
}));

// needed for saving new data
var myRedis = require('redis');                           // additional redis store
var myRedisCli = myRedis.createClient();

myRedisCli.on('error', function (err) {
  console.log('myRedis Error-> '  + err);
});

Is there a way to use connect-redis's redis client? But looks it is binding tightly with session .

I can not find information on this situation. Hope someone can help, thanks!

Upvotes: 2

Views: 1284

Answers (1)

StevenZ
StevenZ

Reputation: 141

After looking into connect-redis code, I finally found out that an existing redis-client can be passed to it. The doc has mentioned this, but gave no example.

Following code works. First create a redis client as normal, then pass it to session.

var express = require('express');
var session = require('express-session');

var _myRedis = require('redis');                           // additional redis store
var myRedisCli = _myRedis.createClient();

// pass the express to the connect redis module
// allowing it to inherit from session.Store
var RedisStore = require('connect-redis')(session);

...

app.use(session({
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  secret: SESSION_SECRET,
  store: new RedisStore({client: myRedisCli})
}));

Upvotes: 3

Related Questions