Redis unable to connect with env port - node.js

I'm trying to create a Redis client. However whenever I do:
const REDIS_PORT = process.env.PORT || 6379;
const client = redis.createClient(REDIS_PORT);
I get AbortError: Ready check failed: Fatal error encountered. Command aborted. It might have been processed.
However if I do:
const REDIS_PORT = 6379;
const client = redis.createClient(REDIS_PORT);
It connects properly. Why do I get this error when I put process.env.PORT?

Assign the desired value to the port key, use this code for create client
redis.createClient({port : REDIS_PORT})
you can check the documentation
const redis = require('redis');
const client = redis.createClient({
host: '127.0.0.1',
port: <port>
});

Related

Problems with migrating to Redis 4.x in Node

I am trying to migrate my google cloud app engine from Redis 3.x to 4.x. However, it appears that there have been some major changes in Redis 4.x. It appears that the client no longer autoconnect and there have been some chnages to the syntax. Here's what I have run
'use strict';
import {createClient} from 'redis';
// These are just values stored in environment variables.
const REDISHOST = process.env.REDIHOST;
const REDISPORT = process.env.REDIPORT;
const REDISAUTH = process.env.REDISAUTH;
const redisClient.createClient();
redisClient.host = REDISHOST;
redisClient.port = REDISPORT;
redisclient.auth = REDISAUTH;
redisClient.on('error', (err) => console.error(`##### REDIS ERR: ${err}.`));
await redisClient.connect();
I can tell that host, port, and auth is being set in redisClient, but when I connect, it tries to connect to localhost and fails. Any idea what I am missing here?
You need to pass the connection information in the call the createClient():
const redisClient = createClient({
socket: {
host: REDISHOST,
port: REDISPORT
},
password: REDISAUTH
})
There are lots of options for connecting. They are all detailed in the client configuration guide.

Redis Cloud and connect-redis: the client is closed

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?
was stuck on same issue and found some luck. have used 'ioredis' module instead of redis which worked seamlessly.
const redis = require('ioredis');
const redisClient = redis.createClient({host:'your host address',port:your port,username:'',password:''});
redisClient.on('connect',() => {
console.log('connected to redis successfully!');
})
redisClient.on('error',(error) => {
console.log('Redis connection error :', error);
})
module.exports = redisClient;
When you create a client using redis.createClient, you need to use url instead of host, port.
refer to basic-example
it showing url format
redis[s]://[[username][:password]#][host][:port][/db-number]
in your case, it might be like this
var url = `redis://<YourUsername>:${process.env.REDIS_PASSWORD}#${process.env.REDIS_HOSTNAME}:${parseInt(process.env.REDIS_PORT)}`
redis.createClient({
url: url
});
Using host, port option must be the old version.
Option 1: switch the order of the calls to auth and connect
From the Node Redis client documentation:
When connecting to a Redis server that requires authentication, the AUTH command must be sent as the first command after connecting.
You should therefore switch the order of the calls to redisClient.auth and redisClient.connect.
Option 2: remove the call to auth
However, the documentation for the password property of createClient options states:
If set, client will run Redis auth command on connect.
As you are supplying password to createClient, you could alternatively just remove the explicit call to auth.
You must do await redisClient.connect() before you access the client. Try to move your redisClient.connect() just after you create it.
try this -->
var options = {
client: redis.createClient({
url : process.env.REDIS_URL,
legacyMode: true,
})};
you can make your url as 'redis://host:port'
import { createClient } from "redis";
const redisClient = createClient({
url: "redis://localhost:6379",
});
const start = async () => {
await redisClient.connect();
};
start();
export default redisClient;

How to troubleshoot problem with setting WebRTC server on vps?

I wrote a simple node express server for webRTC using peerjs-server and simple client using peerjs. Everything works fine on localhost, but when I try it on vps, I get error:
Firefox can't connect with server ws://my.vps/peerjs/peerjs?key=peerjs&id=hj3hpekwaa38fr00&token=ymtfvhagiw
PeerJS: Socket closed.
PeerJS: ERROR Error: Lost connection to server.
Error: "Lost connection to server."
emitError https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:16426
_initializeServerConnection https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:12260
emit https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:25516
onclose https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:19350
Server:
const express = require('express');
enter code here`const app = express();
const ExpressPeerServer = require('peer').ExpressPeerServer;
app.use(express.static('./public'));
const server = app.listen(80, () => { // 3000 on localhost
console.log('Express server listen on port ' + 80);
});
const options = { debug: true };
const peerserver = ExpressPeerServer(server, options);
app.use('/peerjs', peerserver);
app.use('/*', express.static('./public/index.html'));
Client:
var peer = new Peer('', {
host: location.hostname,
port: location.port || (location.protocol === 'https:' ? 443 : 80),
path: '/peerjs',
debug: 3
});
peer.on('open', function (id) {
console.log(id);
});
Any help appreciate.
It looks like you are connecting with server ws://my.vps/, which is a web socket to a server at http://my.vps/ which doesn't seem to exist.
It should probably also be using https (or wss)

How do i get the redis store client from socket-io-redis?

socket-io-redis use redis inside to connect, I wonder how can i get the redis store client from the library so that i can use that client to store key value pairs in redis.
var redis = require('socket.io-redis');
var socketio = require('socket.io');
io = socketio.listen(app);
io.adapter(redis({ host: 'localhost', port: 6379 }));
I am using node cluster model, So i do not want to create a new redis client as i already have one.
It's shown here:
var adapter = redis({ host: 'localhost', port: 6379 });
var pubClient = adapter.pubClient;
io.adapter(adapter);
There's also an equivalent adapter.subClient, but you shouldn't use that (clients running in "subscribe" mode shouldn't be used for regular Redis commands).
I'm not sure if it's wise to use the pubClient to issue commands, either. Redis can handle multiple connections just fine, and it's easy to create a new client from the pubClient instance:
var pubClient = adapter.pubClient.duplicate();

socket.io-redis giving error on heroku

i am trying to deploy my app on heroku.i added redistogo addon in my app.it is based on node.js and express.
i write a small code
var redis = require('socket.io-redis');
var io = require('socket.io')(server);
io.adapter(redis(process.env.REDISTOGO_URL));
but on last line i am getting error:
Error: Redis connection to redistogo:6379 failed - getaddrinfo ENOTFOUND redistogo
can any one help why i am facing this error and get rid of this error.6379 is default port but my redistogo url doesn't has 6379 port no.it's port no is 10281.
Is this a bug in socket.io-redis module or i am doing something wrong ??
If your Redis is running on port 10281 you need to set it when initializing adapter.
var io = require('socket.io')(3000);
var redis = require('socket.io-redis');
io.adapter(redis({ host: process.env.REDISTOGO_URL, port: 10281 }));
Check out documentation https://github.com/automattic/socket.io-redis#adapteropts
If redis DB has a password then it's better to opt for
var redis = require('redis').createClient;
var adapter = require('socket.io-redis');
var pub = redis(port, host, { auth_pass: "pwd" });
var sub = redis(port, host, { detect_buffers: true, auth_pass: "pwd"
});
io.adapter(adapter({ pubClient: pub, subClient: sub }));
in case of heroku enter host as
redis://redistogo:XXXXXXXXX#beardfish.redistogo.com
and port : provided in redistogo_url
and now it's working great.

Resources