javascriptexpressredisexpress-sessionredisjson

Can RedisJson be used to store express-session data instead of Redis


I am trying to manually access the express-session data instead of using req.session.reload() and req.session.save(). I want to use Redisjson instead of default redis. I have the issue of the express-sesssion setting data using .get() instead of .json.get() (.get saves it as a string, which means I cannot access the session through client.json.get().

fFr reference: in express-session session.js the store is saved using:

defineMethod(Session.prototype, 'save', function save(fn) {
  this.req.sessionStore.set(this.id, this, fn || function(){});
  return this;
});

I set the store using this code:

const RedisStore = require("connect-redis").default;
const { createClient } = require("redis");
require("dotenv").config();

const RedisClient = createClient({
    url: `redis://localhost:${process.env.REDISPORT}`
});

RedisClient.connect();
const store = new RedisStore({ client: RedisClient });
const RedisJsonGet = RedisClient.json.get.bind(RedisClient.json);
const RedisJsonSet = RedisClient.json.set.bind(RedisClient.json);


const sessionmiddleware = session(
    {
    store: store,
    secret: crypto.randomBytes(32).toString("hex"),
    resave: false,
    saveUninitialized: true
    }
)

I can access RedisClient.json methods as shown in RedisJsonGet and Set, but if i tried to access them in the express-session they are undefined.

What can I do to be able to access them inside express-session?


Solution

  • I ran into this last year and wrote a module that is pretty much just connect-redis but that uses JSON.

    https://github.com/guyroyse/connect-redis-stack

    I realize this answer is a plug of my own software but it does solve the problem you are looking for. I've not maintained or promoted this much as it just does what it does, but if you find it useful feel free to take what you need.