redis freezes node server when connected
Asked Answered
S

1

5

I am trying to use redis to store sessions with express-session. Here is the code:

//Imports
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const logger = require('morgan');

//Connect to Redis
const redis = require('redis');
let RedisStore = require('connect-redis')(session);
let redisClient = redis.createClient();
redisClient.connect();
redisClient.on('connect', () => console.log('Connected to Redis..'));

app.use(
  session({
    store: new RedisStore({ client: redisClient }),
    saveUninitialized: false,
    secret: 'keyboard cat',
    resave: false,
  })
);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));

app.get('/', function (req, res) {
  var body = '';
  console.log(req.session);
  if (req.session.views) {
    ++req.session.views;
  } else {
    req.session.views = 1;
    body += '<p>First time visiting? view this page in several browsers :)</p>';
  }
  res.send(
    body + '<p>viewed <strong>' + req.session.views + '</strong> times.</p>'
  );
});

app.listen(3000, () => console.log('App is listening on port 3000'));

Whenever I start my application, it freezes. I have checked the redis-cli and pinged it with the response 'PONG'. redis-server is starting just fine. Whenever I remove the following lines:

redisClient.connect();
redisClient.on('connect', () => console.log('Connected to Redis..'));

the app crashes whenever I hit the "/" route. But if I had those lines in, the app just hangs there and doesn't do anything. I checked the docs here and they said you need to connect before any command:

https://github.com/redis/node-redis/blob/HEAD/docs/v3-to-v4.md#no-auto-connect

And the code I'm running is right from the connect-redis npm page:

https://www.npmjs.com/package/connect-redis

I'm not sure why the server is freezing. It works fine if I remove store from the session so it's definitely something to do with redis but on the node side. The redis server is running fine on the localhost. Any suggestions?

**UPDATE

I checked the connect-redis repo issues and I found that someone else is having the same problem as me. The problem will be resolved in the next commit:

https://github.com/tj/connect-redis/issues/336

Sialoid answered 1/12, 2021 at 1:35 Comment(0)
S
11

This is currently a known issue. Currently connect-redis is not compatible with the latest version of node redis. https://github.com/tj/connect-redis/issues/336

Add the following to your client to fix this issue until patched:

const client = createClient({
    legacyMode: true
});
Sialoid answered 1/12, 2021 at 14:57 Comment(1)
August 2022 and this was still the case for me.. 🤯Gerund

© 2022 - 2024 — McMap. All rights reserved.