Search code examples
node.jsexpressredisexpress-sessionconnect-redis

express session and connect redis error on saving session redis store (TypeError: this.client.set is not a function)


I am trying to implement express-session and connect-redis to manage session for my node application.

I already follow instructions on how to apply the express-session with connect-redis

app.js

import express from "express";
import http from "http";
import session from "express-session";
import connectRedis from "connect-redis";

const app = express();
const StoreRedis = connectRedis(session);

sessionConfig.setStorage(new StoreRedis({ client: redisService() }));


app.use(session(sessionConfig.getConfig()));

const server =
    appConfig.SECURE == true
      ? https.createServer({}, app)
      : http.createServer(app);

app.use("/", router);

  server.listen(appConfig.GAME_SERVICE_PORT, appConfig.SERVER_HOST, () => {
    const protocol = appConfig.SECURE == true ? "https" : "http";
    console.log(
      `Server started ${protocol}://${appConfig.SERVER_HOST}:${appConfig.GAME_SERVICE_PORT}`
    );
  });

redis-service.js

import { createClient } from "redis";
export default async () => {
  // redis[s]://[[username][:password]@][host][:port][/db-number]
  const redisClient = createClient({
    // url: `redis://${REDIS_USERNAME}:@${REDIS_PASSWORD}${REDIS_HOST}:${REDIS_PORT}`,
    legacyMode: true,
  });

  redisClient.on("error", function (err) {
    console.log("Could not establish a connection with redis. " + err);
  });
  redisClient.on("connect", function (err) {
    console.log("Connected to redis successfully");
  });

  await redisClient.connect();

  return redisClient;
};

route.js

    export default (request, response, next) => {
  request.session.key = "aaaaa";
  response.render("game", {
    title: "title of the game",
  });
};

SERVER LOG

WHEN I TRIED TO ACCESS THE URL FOR THE ROUTE GIVE ME THIS ERROR ERROR LOG

WHEN I TRY TO SAVE DATA TO THE REDIS IT CAN SAVE DATA

await redisClient.set("input", "value");

MY PROBLEM IS ON THE REDIS STORE.

package.json node version 16.16.0

enter image description here

THANKS FOR THE HELP.


Solution

  • redisService() returns Promise<RedisClient>, but StoreRedis expected client to be RedisClient.

    I'm pretty sure that if you can use import you can use top-level-await as well, so I'll use it in the solution below:

    // `redis-service.js`
    import { createClient } from 'redis';
    
    const client = createClient({
      // ...
      legacyMode: true
    });
    
    client.on('error', (err) => console.log('Could not establish a connection with redis', err));
    client.on('connect', () => console.log('Connected to redis successfully'));
    
    await client.connect();
    
    export default client;
    
    // `app.js`
    // ...
    import redisClient from './redis-service.js';
    // ...
    sessionConfig.setStorage(new StoreRedis({ client: redisClient }));
    // ...