Not able to connect to heroku redis - node.js

const redis = require("redis");
let client = redis.createClient({
host: process.env.host,
port: process.env.port,
password:process.env.password
});
(async () => {
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
console.log("connected to redis")
})();
I have added redis-heroku addon to my project, Now I am trying to access it from my code but its giving me this error: "AuthError: ERR Client sent AUTH, but no password is set".
Also when I am trying to connect from terminal, I am able to connect to it but when I type any redis command , I get this "Error: Connection reset by peer".
If I am using this on my localsystem and local redis server its working fine
it will be helpful if anyone can provide me a working code of heroku redis, I think redis has two urls: REDIS_URL, REDIS_TLS_URL. The problem might be arising because of this tls(more secure)
Kinldy help me
Thanks

Heroku redis does not expose a host, port, and password variables. Instead they expose a REDIS_URL that contains all of those things in one string.
I believe you need to call createClient like this...
createClient({
url: process.env.REDIS_URL
});

In node-redis v4 the host and port should be inside a socket object, not directly on the main config object (see https://github.com/redis/node-redis/blob/master/docs/client-configuration.md):
const client = redis.createClient({
socket: {
host: process.env.host,
port: process.env.port
},
password: process.env.password
});

Related

Connecting to redis using tls (ssl) and auth_token password in nodeJS

I am trying to connect to a redis instance in aws. I can connect to it using something like
redis-cli -h localhost -p 6379 -a <auth_token> --tls PING
However when I try this using node (redis library v4.2.0) doing something like this, it hangs
const redis = require("redis");
(async () => {
const client = redis.createClient( {
auth_pass:
"<auth_token>",
tls: { servername: "localhost", port: 6379 },
});
client.on("error", (err) => {
console.log("Redis Client Error", err);
});
client.connect();
console.log(await client.ping());
})();
Portforwarding is setup for redis in aws, which is why localhost is used.
The auth token is the same token I entered to the sparkleformation when redis was configured. both resting and transit encryption has been configured as well.
I have been trying to poke around on google for an answer, however there seem to be a lot of old documentation out there and none of the new ones are clear as to how to get a connection working using tls and an auth token. Any idea how to get this working?
If anybody is running into the same issue, I was able to get it working using ioredis instead.
const Redis = require("ioredis");
(async () => {
const redisRef = new Redis("rediss://:<auth_token>#localhost:6379");
console.log(await redisRef.ping());
})();
and setting this environment variable when running locally:
export NODE_TLS_REJECT_UNAUTHORIZED=0

Redis Connection Error with Heroku Redis Instance: Redis connection to failed - read ECONNRESET heroku instance

I have a node js app. And I use Redis from Heroku Redis(with async-redis library).
Actually, I have two different Heroku accounts and two different Node.js apps hosted by Heroku. But except Redis credentials, both apps are the same code.
The interesting thing on my app I can connect to first Heroku Redis instance. But I can't connect to new Heroku Redis instance. Besides I deleted and created new instances, bu they don't work.
The error is:
Error: Redis connection to redis-123.compute.amazonaws.com:28680 failed - read ECONNRESET\n
at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
My connection statement like this:
var redisPassword = 'password123';
var redisOptions = { host: 'redis-123.cloud.redislabs.com', port: '17371', auth_pass: redisPassword }
//var redisPassword = 'password123';
//var redisOptions = { host: 'redis-123.compute.amazonaws.com', port: '28680', auth_pass: redisPassword }
const client = redis.createClient(redisOptions);
client.on('connect', function () {
console.log('Redis client connected');
});
client.on('error', function (err) {
console.log('An error on Redis connection: ' + err);
});
As I can see there is the only thing that different on Heroku Redis instances. My first Redis instance hosts at cloud.redislabs.com but the second instance(that i can't connect) hosts at compute.amazonaws.com.
Any help will be much appreciated.
I encountered this situation and it turned out the with "Heroku Redis" connecting via TLS worked (the url that starts with rediss) once I adjusted my client code to connect following the example provided in the Heroku redis docs:
https://devcenter.heroku.com/articles/connecting-heroku-redis#ioredis-module
const Redis = require("ioredis");
const client = new Redis(process.env.REDIS_URL, {
tls: {
rejectUnauthorized: false
}
});
Where process.env.REDIS_URL is rediss://<details>
I couldn't find the root problem. But after comment of Chris, I checked again Heroku Redis addons I used.
Heroku Redis gives me an instance from amazonaws.com, and Redis Enterprise Cloud gives me an instance from redislabs.com. When I added and used Redis Enterprise Cloud, I could connect to it.
But Heroku Redis's connection problem still is a secret for me.

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 can I connect redis cloud instance to bull queue?

I am trying to connect redis free cloud instance with bull queue but getting error as it is not able to connect.
I tried below code:
const Bull = require("bull");
const emailQueue = new Bull("email", {
redis: "",
});
For above code it is giving error Error: connect ECONNREFUSED 127.0.0.1:6379 message.
Also tried something like this: using tls field but did not work.
const Bull = require("bull");
const emailQueue = new Bull("email", {
redis: {
port: "",
host: "",
tls: { rejectUnauthorized: false },
},
});
Note: I am using redis free cloud instance with bull queue and also download redis insight desktop application. I have added database to redis insight desktop app and it is connected but in node application it is not working. Am I missing any config?
Firstly, you have to ensure that your redis server is running locally since you want to connect to 127.0.0.1:6379.
Secondly, to get the connection error you might be having, you can try this:
emailQueue.on('error', (error) => {
console.log(error);
})
For me, I had no issue connecting to my local Redis server but I could not connect to remote Redis servers especially Redis labs and AWS ElasticCache. From the error message, I realized that I needed extra authentication and I just provided the host, port, username, and password for Redis Labs while I only needed to provide a host, port, and password for AWS ElasticCache, leaving the username as an empty string in my env.
const {
REDIS_HOST,
REDIS_PORT,
REDIS_USERNAME,
REDIS_PASSWORD,
} = process.env
const emailQueue = new Queue('email', {
redis: {
port: REDIS_PORT,
host: REDIS_HOST,
username: REDIS_USERNAME,
password: REDIS_PASSWORD
}
});

Can't connect to database with process.env variables but process.env vars print in log

I'm connecting to a redshift database with Node/express. I put the variables to connect to the database in a .env file, and on my local machine, I'm able to connect to the website on localhost.
However, when I upload the files to the server and change the clientConfiguration, it no longer works, even after I've changed my require('dotenv').config({path: }) to the correct path. I'm pretty sure the path is correct because process.env.HOST will print in the logs.
This error will show up: password authentication failed for user "root"
This is the hardcoded part that works.
var clientConfiguration = {
user: "user",
database: "database",
password: "password",
port: 1234,
host: "hosturl.com",
};
When I swap this part in, it no longer works.
var clientConfiguration = {
user: process.env.USER,
database: process.env.DATABASE,
password: process.env.PASSWORD,
port: process.env.PORT,
host: process.env.HOST,
};
I thought it was because process.env variables get read in as strings, but that didn't help even after I used parseInt(process.env.PORT) -- I also didn't need the parseInt on my local machine, so I dont understand the
Are you calling dotenv.config() as early as possible? I call it right after creating a new Express instance and it usually works.
Also, not sure if this is the 'accepted way', but I have had a similar issue before and found making an async dotenv.config() call inside the IIFE where I start my server solved the issue:
//AWAIT DB CONNECTION BEFORE STARTING SERVER
(async function () {
try {
await dotenv.config();
await connectDB();
app.listen(PORT, ()=> {
console.log(`Server listening in ${MODE} mode on ${PORT}`);
});
} catch (err) {
console.log(`Failure to start server: ${err}`);
}
})();
connectDB() is my attempt to connect to a MongoDB database via mongoose.connect(). Obviously not the ideal solution as you want to call it earlier, but it did work.

Resources