node.jsredisconnect-redis

Trying to use connect-redis but getting an error


I have the following code

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

// Initialize Redis client
let redisClient = createClient({ url: process.env.REDIS_URL });
redisClient.connect().catch(console.error);

let redisStore = new RedisStore({
  client: redisClient,
  prefix: "test:",
});

app.use(
    session({
      store: redisStore,
      secret: process.env.SESSION_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: {
        secure: process.env.NODE_ENV === "production",
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24, // 1 day
      },
    })
);

I'm trying to use connect-redis v9.0 but I get the error

let redisStore = new RedisStore({
                 ^

TypeError: RedisStore is not a constructor

What am I doing wrong?

I recently upgraded my node js version to the latest one so I'm guessing it has to do with that.


Solution

  • const RedisStore = require("connect-redis").default;
    

    require("connect-redis").default will import the default object in RedisStore. A simple console.log(RedisStore ) will help you see its content.

    If you wish to use this way, below code will help:

    let redisStore = new RedisStore.RedisStore({...});
    

    But a better way is to only import stuff you require and for that const { RedisStore } = require('connect-redis'); will help.

    Here you are specifically importing RedisStore from the default object.