I currently build a website using Express and want to use redis cloud database to save userID in session. The redisClient is created in redisClient.js and after that i pass it to redisStore in session in app.js. Here is the code:
redisCLient.js
const redis = require("redis");
let redisClient = redis.createClient({
host: process.env.REDIS_HOSTNAME,
port: parseInt(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD
});
redisClient.on('error', function(err) {
console.log('*Redis Client Error: ' + err.message);
});
redisClient.on('connect', function(){
console.log('Connected to redis instance');
});
(async () => {
await redisClient.auth(process.env.REDIS_PASSWORD)
.catch(err => {console.log('Redis auth error: ' + err.message)});
await redisClient.connect()
.catch(err => {console.log('Redis connect error: ' + err.message)});
})();
module.exports = redisClient;
app.js
const session = require("express-session");
const redisStore = require('connect-redis')(session);
const redisClient = require('./session-store/redisClient');
...
app.use(cookieParser());
app.use(session({
store: new redisStore({client: redisClient, ttl: 3600 * 24 * 30}),
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
resave: false
}));
The problem is: upon starting the server i got error messages log in console like this:
Redis auth error: The client is closed
*Redis Client Error: connect ECONNREFUSED 127.0.0.1:6379
*Redis Client Error: connect ECONNREFUSED 127.0.0.1:6379
*Redis Client Error: connect ECONNREFUSED 127.0.0.1:6379
*Redis Client Error: connect ECONNREFUSED 127.0.0.1:6379
...
I used this guide to set up redis cloud and assign dotenv variables (host, port and password). I have debugged and the dotenv is working fine and I have host, port and password variables correct.
But the problem still remains. I still get The client is closed and connect ECONNREFUSED 127.0.0.1:6379 error as in console log above. How can i fix this?
6
Answers
Option 1: switch the order of the calls to
auth
andconnect
From the Node Redis client documentation:
You should therefore switch the order of the calls to
redisClient.auth
andredisClient.connect
.Option 2: remove the call to
auth
However, the documentation for the
password
property ofcreateClient
options states:As you are supplying
password
tocreateClient
, you could alternatively just remove the explicit call toauth
.You must do
await redisClient.connect()
before you access the client. Try to move yourredisClient.connect()
just after you create it.was stuck on same issue and found some luck. have used ‘ioredis’ module instead of redis which worked seamlessly.
you can make your url as ‘redis://host:port’
When you create a client using
redis.createClient
, you need to useurl
instead ofhost
,port
.refer to basic-example
it showing
url
formatredis[s]://[[username][:password]@][host][:port][/db-number]
in your case, it might be like this
Using
host
,port
option must be the old version.