connect-redis redisClient.connect() connecting to wrong IP - node.js

I am getting the following error message.
app | Redis error: Error: connect ECONNREFUSED 127.0.0.1:6379
app | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
app | errno: -111,
app | code: 'ECONNREFUSED',
app | syscall: 'connect',
app | address: '127.0.0.1',
app | port: 6379
app | }
It is connecting to 127.0.0.1, even though I have hard-coded the ip address as 172.19.0.3. I'm not sure if it makes a difference, but the app, and redis db are both in docker containers. I have supplied the external IP for the redis container.
// Session / Redis
const session = require('express-session');
const redisStore = require('connect-redis')(session);
// redis#v4
const { createClient } = require("redis")
const redisClient = createClient({
legacyMode: true,
host: '172.19.0.3'
});
redisClient.connect()
.catch(console.error)
.then(() => {
console.log('Connected to Redis server successfully');
});
app.use(
session({
secret: process.env.SESSION_SECRET,
name: '_redisSessionId',
resave: false,
saveUnitialized: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 60000 // 30 minutes
},
store: new redisStore({
host: '172.19.0.3', //process.env.REDIS_HOST,
port: 6379,
client: redisClient,
ttl: 86400
})
}))
Any help is greatly appreciated.

According to the documentation your createClient options should look like:
{
url: 'redis://172.19.0.3',
legacyMode: true,
}
and creating the connect-redis store should look like:
new redisStore({ client: redisClient });

Related

SSL Error - Alert number 80 - When calling server from client

I am a newbie in web development, I developed my first basic CRUD app. It works as expected in my local. As a portfolio item, I wanted create an actual website. I bought domain name & SSL certificate etc, deployed my back end and front end etc. However I am struggling with an issue for the last couple of days. Please see the details below
Background Info
Server: I have a nodejs application on Heroku (example.com). I bought an ssl certificate for my domain (i.e. example.com). I inserted certificate and intermediate certificate in Heroku and linked with my back end.
Client: I deployed my React & nextjs frontend on Vercel (subdomain.example.com). Vercel is creating its own certificate for subdomain.example.com
My issue is that I am receiving the following error in my website. After I wait couple minutes and refresh the error disappears. If I don't use it for some time again, the error reappears.
[Network] FetchError: request to https://example.com/graphql failed, reason: write EPROTO 139801265354624:error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL alert number 80
See below my code for nodejs
const conn = await createConnection({
type: "postgres",
url: process.env.DATABASE_URL,
host: process.env.PG_HOST,
username: process.env.PG_USER,
password: process.env.PG_PASSWORD,
port: parseInt(process.env.PORT),
database: process.env.PG_DATABASE,
logging: true,
migrations: [path.join(__dirname, "./migrations/*")],
entities: [Bank, User, Report],
ssl: __prod__ ? {rejectUnauthorized: false} : false
})
const redisStore = connectRedis(session);
const redis = new Redis(process.env.REDIS_URL);
app.set("trust proxy", 1)
app.use(cors({
origin: __prod__ ? process.env.CORS_ORIGIN : "http://localhost:3000",
credentials: true
}))
app.use(
session({
name: COOKIE_NAME,
store: new redisStore({
client: redis,
disableTouch: true
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10,
httpOnly: true,
sameSite: "none",
secure: __prod__,
domain: __prod__ ? process.env.DOMAIN : undefined
} as CookieOptions ,
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
resave: false
})
)
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [BankResolver, UserResolver, ReportResolver],
validate: false
}),
context: ({req, res}): MyContext => ({req, res, redis})
})
await apolloServer.start()
apolloServer.applyMiddleware({app, cors: false});
app.listen(parseInt(process.env.PORT), () => console.log("Server listening on port 4000"));
}

Heroku deployement error connect ECONNREFUSED 127.0.0.1:27017

This is my code for mongodb atlas connection, it shows connection successful but later when I click on some tab the app crashes. I m deploying app through heroku and i have given the error below .app runs fine on localhost but crashes on the heroku website. It sometimes allows and opens some pages but crashes right after that , i have tried fixing environemnt variables on heroku website but that was of no help so i switched to just using the mongo connection link through the variable. Any help is appreciated.
I discovered that the server throws the error of not being able to connect after exactly 30 seconds but still cant find what is causign the error
if (process.env.NODE_ENV !== "production") {
require('dotenv').config();
}
const sanitize = require('express-mongo-sanitize');
// const dbURL = process.env.DB_URL;
const session = require('express-session');
const MongoStore = require('connect-mongodb-session')(session);
const dbURL = "mongodb+srv://RohanGupta:****************#*****.****.mongodb.net/oddevegame?retryWrites=true&w=majority";
mongoose.connect(dbURL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => {
console.log("Connected Mongo Successfully")
})
.catch(err => {
console.log("Uh Oh couldnt connect mongo!!")
console.log(err);
})
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, '/resources')));
app.use(session({
store: new MongoStore({
url: dbURL,
touchAfter: 24 * 3600
}),
name: "blah",
secret: 'this is secret',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
// secure: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}));
2021-06-20T07:27:23.462279+00:00 heroku[web.1]: State changed from starting to up
2021-06-20T07:27:23.230556+00:00 app[web.1]: Listening on PORT 4000
2021-06-20T07:27:23.502833+00:00 app[web.1]: Connected Mongo Successfully
2021-06-20T07:27:53.221633+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:698
2021-06-20T07:27:53.221654+00:00 app[web.1]: throw error;
2021-06-20T07:27:53.221655+00:00 app[web.1]: ^
2021-06-20T07:27:53.221655+00:00 app[web.1]:
2021-06-20T07:27:53.221656+00:00 app[web.1]: Error: Error connecting to db: connect ECONNREFUSED 127.0.0.1:27017
2021-06-20T07:27:53.221656+00:00 app[web.1]: at /app/node_modules/connect-mongodb-session/index.js:78:17

Nodemailer working on localhost, but not on web host, Error: connect ECONNREFUSED

I have been using nodemailer to send emails from my node js app, it used to work perfectly on localhost and it still does. I deployed the server to my online host, it didn't work giving me this error
{ Error: connect ECONNREFUSED 172.253.112.108:465
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1174:14)
errno: 'ECONNREFUSED',
code: 'ECONNECTION',
syscall: 'connect',
address: '172.253.112.108',
port: 465,
command: 'CONN' }
I have tried to look for solutions (XOauth2, using older version of nodemailer, setting environment variables) but none are working! what should i do to resolve this?
I had the config below:
let transporter = nodemailer.createTransport({
name: mydomain.com,
pool: true,
host: mydomain.com, //as recommended by my host provider
port: 465,
secure: true,
auth: {
user: info#mydomain.com,
pass: MAILER_PASSWORD,
},
tls: {
rejectUnauthorized: false,
},
});
The problem was with accessing the port 465 on the host.
changed my config to following solved the problem:
let transporter = nodemailer.createTransport({
name: mydomain.com,
pool: true,
host: mail.mydomain.com, //<----change
port: 587, //<----change
secure: false, //<----change
auth: {
user: info#mydomain.com,
pass: MAILER_PASSWORD,
},
tls: {
rejectUnauthorized: false,
},
});

heroku eureka-js-client node- Spring Cloud Netflix Support -

What I want to achieve is:
registering a node.js service in my eureka-server in heroku.
So far i can register a regular eureka-client in my eureka-server in heroku, without problems. But i am getting really confused with the configuration when try with node.js service...
I thought eureka-js-client was the solution, no success so far...
Code below.
const express = require('express');
const path = require('path');
const port = process.env.PORT || 3090;
const app = express();
app.use(express.static(__dirname));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'))
});
const Eureka = require('eureka-js-client').Eureka;
const eureka = new Eureka({
instance: {
app: 'sheila',
hostName: 'localhost',
ipAddr: '127.0.0.1',
statusPageUrl: 'http://localhost:5000',
healthCheckUrl: 'http://localhost:5000/health',
port: {
'$': 5000,
'#enabled': 'true',
},
vipAddress: 'myvip',
dataCenterInfo: {
'#Class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
name: 'MyOwn',
},
},
eureka: {
host: 'localhost',
port: 8761,
servicePath: '/eureka/apps/',
},
});
eureka.logger.level('debug');
eureka.start(function(error){
console.log(error || 'complete');
});
// ------------------ Server Config --------------------------------------------
var server = app.listen(5000, function () {
var port = server.address().port;
console.log('Listening at %s', port);
});
First i've tried locally after running docker run -it -p 8761:8761 springcloud/eureka on my docker console. But i get this error:
Problem making eureka request { [Error: connect ECONNREFUSED 127.0.0.1:8761]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8761 }
if i run it as it is from a heroku service, It does not execute :( :(
I also tried by substituting the host for the url of my heroku eureka server, but then i get 401 or 404 errors. The eureka server requires a password which i added in my heroku client js .
Any ideas?
You need to include an instanceId which should be a unique identifier of this instance.
const eureka = new Eureka({
instance: {
instanceId:'sheila',
app: 'sheila',
hostName: 'localhost',
ipAddr: '127.0.0.1',
statusPageUrl: 'http://localhost:5000',
healthCheckUrl: 'http://localhost:5000/health',
port: {
'$': 5000,
'#enabled': 'true',
},
vipAddress: 'myvip',
dataCenterInfo: {
'#Class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
name: 'MyOwn',
},
},
eureka: {
host: 'localhost',
port: 8761,
servicePath: '/eureka/apps/',
},
});

redis session not working on server

I am using redis for session in my node.js express app. It works fine on my dev box, but on production, it seems redis sessions are not being saved.
I'm not seeing any kind of error, other than I cannot login.
Redis is running w/ same configuration. But when I run redis-cli and type 'select 1' (the db) and KEYS '*' I get nothing.
var RedisStore = require('connect-redis')(express);
app.use(express.session({
store: new RedisStore({
host: cfg.redis.host,
db: cfg.redis.db
}),
secret: 'sauce'
}));
cfg.redis.host is localhost
and cfg.redis.db is 1
This is the error I get when I run redis-cli monitor
Error: Protocol error, got "s" as reply type byte
A few suggestions. Are you sure Redis uses the same port and password in production? If you're using SSL with a service like Heroku, you need to set proxy: true to have Express treat cookies that arrive after after earlier SSL termination.
.use(express.session({
store: new RedisStore({
port: config.redisPort,
host: config.redisHost,
db: config.redisDatabase,
pass: config.redisPassword}),
secret: 'sauce',
proxy: true,
cookie: { secure: true }
}))
I require the following config.js file to pass on Redis config values:
var url = require('url')
var config = {};
var redisUrl;
if (typeof(process.env.REDISTOGO_URL) != 'undefined') {
redisUrl = url.parse(process.env.REDISTOGO_URL);
}
else redisUrl = url.parse('redis://:#127.0.0.1:6379/0');
config.redisProtocol = redisUrl.protocol.substr(0, redisUrl.protocol.length - 1); // Remove trailing ':'
config.redisUsername = redisUrl.auth.split(':')[0];
config.redisPassword = redisUrl.auth.split(':')[1];
config.redisHost = redisUrl.hostname;
config.redisPort = redisUrl.port;
config.redisDatabase = redisUrl.path.substring(1);
console.log('Using Redis store ' + config.redisDatabase)
module.exports = config;

Resources