Heroku deployement error connect ECONNREFUSED 127.0.0.1:27017 - node.js

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

Related

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

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 });

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"));
}

Error when using with Massive.js in Node.js

I've been using massive.js within node for a couple months now and never ran into this error. I am completely stumped. Here is the code I am working with:
require('dotenv').config()
const{CONNECTION_STRING, SERVER_PORT, SESSION_SECRET} = process.env
const massive = require('massive')
const express = require('express')
const app = express()
const session = require('express-session')
app.use(express.json())
app.use(session({
resave: true,
saveUninitialized: false,
secret: SESSION_SECRET,
cookie: {
maxAge: 1000 * 60 * 60 * 2
}
}))
massive({
connectionString: CONNECTION_STRING,
ssl: {
rejectUnauthorized: true
}
})
.then(dbInstance => {
app.set('db', dbInstance)
app.listen(SERVER_PORT, () => console.log(`Server is bumping on ${SERVER_PORT}`))
})
.catch(err => console.log(err))
When I run nodemon, I get an error: "Error: self signed certificate". I know it has something to do with massive as when I take it out, nodemon connects to the server. When I change the value of rejectUnauthorized to false I get this error: "TypeError: client.ref is not a function". I have tried running "process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" on the command line and within the code but no luck. Any sort of help would be appreciated.

How to specify the connection string in connect-pg-simple?

The simple example on https://github.com/voxpelli/node-connect-pg-simple shows:
var session = require('express-session');
app.use(session({
store: new (require('connect-pg-simple')(session))(),
secret: process.env.FOO_COOKIE_SECRET,
resave: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));
But when I try it, node complains:
throw new Error('No database connecting details provided to
connect-pg-simple');
How do I specify the connection string?
// I was stuck with the same proble and solved it
// 1-) Connection details
const conObject = {
user: 'mehmood',
password: 'mehmood',
host: 'localhost',// or whatever it may be
port: 5432,
database: 'test_db'
};
// 2-) Create an instance of connect-pg-simple and pass it session
const pgSession = require('connect-pg-simple')(session);
// 3-) Create a config option for store
const pgStoreConfig = {
pgPromise: require('pg-promise')({ promiseLib: require('bluebird') })({
conObject }), // user either this
//conString: 'postgres://mehmood:mehmood#localhost:5432/test_db', // or this
// conObject: conObject,// or this,
// pool: new (require('pg').Pool({ /* pool options here*/}))// or this
}
// 4-) use the store configuration to pgSession instance
app.use(session({
store: new pgSession(pgStoreConfig),
secret: 'jW8aor76jpPX', // session secret
resave: true,
saveUninitialized: true,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));
// Share improve this answer
For me it worked like
conString:'postgres://postgres:password123#localhost:5432/edu';
So the format must be
conString:'postgres://<user>:<database_password>#<hostname>:<port>/<database_name';
For deploying you get a username. If you run on local machine then PostgreSQL

Expiration object in express-session not the correct type?

Every so often, my nodejs application — which uses the express v4.12.2 and express-session v1.13.0 modules — throws the following TypeError exception and crashes:
/app/node_modules/express-session/node_modules/cookie/index.js:136
if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
^
TypeError: opt.expires.toUTCString is not a function
at Object.serialize (/app/node_modules/express-session/node_modules/cookie/index.js:136:56)
at setcookie (/app/node_modules/express-session/index.js:576:21)
at ServerResponse.<anonymous> (/app/node_modules/express-session/index.js:204:7)
at ServerResponse.writeHead (/app/node_modules/on-headers/index.js:46:16)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.res.write (/app/node_modules/compression/index.js:82:14)
at ReadStream.ondata (_stream_readable.js:529:20)
at emitOne (events.js:90:13)
at ReadStream.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:147:16)
at ReadStream.Readable.push (_stream_readable.js:111:10)
at onread (fs.js:1822:12)
at FSReqWrap.wrapper [as oncomplete] (fs.js:614:17)
I'm not sure why this would be an error, since toUTCString() is a function. (Unless opt.expires is not a Date object.)
From testing the application, and also because this seems to involve opt.expires, I am wondering if this happens when a session times out.
Here is how I am setting up sessions:
var express = require('express');
var expressSession = require('express-session');
...
var app = express();
...
app.use(expressSession({
key: 'application.sid',
secret: 'some.secret.string',
cookie: {
maxAge: 60 * 60 * 1000,
expires: 60 * 60 * 1000
},
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions'
}),
saveUninitialized: true,
rolling: true,
resave: true,
secure: true
}));
My goal is to have a session expiration get extended if the user keeps using the application.
Is there something wrong about how I have set this up, or have I run into some bug that would be fixed with a specific combination of versions of modules?
req.session.cookie.expires must be a date not a number.
Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor:
var hour = 3600000;
req.session.cookie.expires = new Date(Date.now() + hour);
req.session.cookie.maxAge = hour;

Resources