heroku DATABASE_URL is undefined in nodejs app - node.js

Heroku site states that the DATABASE_URL is setup automatically for you. I used the command
heroku config
to confirm that the DATABASE_URL is indeed set.
However when I use the pg package command
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
and do a console.log(process.env.DATABASE_URL), the variable reads as undefined.
The other errors that I am getting are:
UnhandledPromiseRejectionWarning: Error: The server does not support SSL connections
The complete code is:
const express = require('express');
require('dotenv').config();
const { Client } = require('pg');
const app = express();
console.log(process.env.DATABASE_URL);
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
client.query('SELECT * FROM customers;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
app.get('/', (req, res) => {
res.send('Hello World')
});
app.listen(4000, () => {
console.log(`Server started on port`);
});
The code works when I use my local postgresql database, but when I try to connect to Heroku's postgres database, the above errors occur. Any suggestions?

Seems you're not crazy... This isn't working for me either, so I dug in, and it just seems... broken.
https://stackoverflow.com/a/19341505/4526479
I see DATABASE_URL defined in the heroku config vars section in the online heroku dashboard. But it's just undefined in the app.

It looks like you're running into issues connecting to the Heroku Postgres database when you run the project locally.
The DATABASE_URL environment variable specified in heroku config exists only on the Heroku server and you don't have the environment variable set locally.
Create a .env file and include your connection string like so
DATABASE_URL=...
Here you can include the connection string for the database hosted on Heroku, or your local Postgres database server. Just make sure SSL is configured correctly

Related

NodeJS to SQL Server Connection not working: socket hang up issue

Here is my complete code for sql connection, all code I have got from stackoverflow issues.
Everywhere, I found the same code is being suggested, hence I also tried with the same.
I have some other application which uses same connection with NextJs and it works fine, however, If I try only with NodeJS code, it gives some socket hang up error (code:'ESOCKET' name:'ConnectionError').
Please make a note that TCP is already configured on remote server and its working fine with other applications.
Any help is appreciated, thank you.
const express = require('express');
const fs = require('fs');
const path = require('path');
const cheerio = require("cheerio");
const sql = require('mssql');
require('dotenv').config(); //to use the env variables
// config for your database
var config = {
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
server: process.env.DATABASE_HOST,
database: process.env.SOMEDB,
port: 14345, // process.env.DATABASE_PORT,
options: {
encrypt: true, // for azure
trustServerCertificate: false // change to true for local dev / self-signed certs
}
};
// make sure that any items are correctly URL encoded in the connection string
let appPool = new sql.ConnectionPool(config);
//I got error on below connect
sql.connect(config).then(function(pool) {
//It never reaches here, it directly goes to the catch block
app.locals.db = pool;
const server = app.listen(3000, function () {
const host = server.address().address
const port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
}).catch(function(err) {
console.error('Error creating connection pool', err)
});
I have the same issue.
Try to use mssql version 6.0.1, it works on my code, but for sure we need to figure out the problem, since we can't think to mantain forever an old version of a package.
I kept trying to find the solution with different different configuration changes.
Finally, I have made a proper config, which worked and now its connecting properly as well as returning the data from the table.
require('dotenv').config(); //to access the process.env params
const sql = require("mssql"); //mssql object
var dbConfig = {
user: "ajay",
password: "abcd123",
server: "your_remote_sql_server_path",
port: 1433,
database: "your_database_name",
options: {
database: 'your_database_name',
trustServerCertificate: true
}
};
try {
//connection config will be used here to connect to the local/remote db
sql.connect(dbConfig)
.then(async function () {
// Function to retrieve the data from table
const result = await sql.query`select top 1 * from table_name`
console.dir(result)
}).catch(function (error) {
console.dir(error);
});
} catch (error) {
console.dir(error);
}
I am not sure what was the exact issue, but as per the previous config and this one, it seems like adding database name to the options has solved the issue.
Please make sure to save all the sensitive data to the .env file. (which you can access as PROCESS.env.parametername)
For me in driver mssql#9.1.1 making encrypt=false worked
const config = {
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
server: process.env.DATABASE_HOST,
database: process.env.SOMEDB,
port: 14345, // process.env.DATABASE_PORT,
options: {
encrypt: false
}
};

Heroku error: "connect ECONNREFUSED 127.0.0.1:3306" when trying to deploy Express + React application

I was trying to deploy my Express + React application to Heroku. Heroku connected successfully with my Github account, then clicking "Deploy Branch" led to "Your app was successfully deployed". But when I went to view my website, it showed:
"Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details".
Here are my logs:
Starting process with command `npm start`
> myproject# start /app
> node backend/index.js
My project SQL server listening on PORT 4000
/app/backend/index.js:22
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
And the index.js which connects to MySQL:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /my-project to see my project')
});
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/my-project', (req, res) => {
connection.query(SELECT_ALL_FACTS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
const SELECT_ALL_FACTS_QUERY = 'SELECT * FROM `my-project`.`my-table`;';
app.listen(4000, () => {
console.log('My project SQL server listening on PORT 4000');
});
What did I do wrong and how could I deploy it?
I think in the below code the localhost should not be used, the localhost will not work in deployment.
const pool = mysql.createPool({
connectionLimit: 10,
//here
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
And another mistake I found is you should use an environment variable to store
port numbers. In production, the port number is assigned by Heroku, if not assigned you
can assign. So your code should be
let port=process.env.PORT||4000
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
you need to add (add-ons) to your heroku account
and connect it to your app.
For example, you can use (JAWS_DB mysql)
By having the following code in your connection:
// import the Sequelize constructor from the library
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
// when deployed on Heroku
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
// localhost
sequelize = new Sequelize(process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
}
module.exports = sequelize;
It passed this stage after I removed if (err) throw err;, still not sure why this happened.
Nithin's answer was taken into account too.
the same errorhappened to me while i was trying to connect to heroku cli and i jus read the heroku config for proxy and that was the case. problem solved by configuring the http and https proxy like
set HTTP_PROXY=http://proxy.server.com:portnumber
or set HTTPS_PROXY=https://proxy.server.com:portnumber

Unable to connect to mongodb database with my heroku app?

I am unable to connect my Node.js app deployed to Heroku with a MongoDB database. It works fine on localhost, but not on Heroku.
In my logs, I see this:
MongoNetworkError: failed to connect to server [authproject-shard-00-01-ybey8.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to authproject-shard-00-01-ybey8.mongodb.net:27017 closed]
custom-environment-variables.json:
{
"db": "Auth_db"
}
default.json:
{
"db": "mongodb://localhost/user"
}
db.js:
const db = config.get("db");
mongoose
.connect(db)
.then(() => console.log("connected to mongodb.."))
.catch(err => console.error("could not connect to mongodb", err));
};
You need to configure an environment variable in your Heroku application.
Run in console:
heroku config:set MONGODB_URI='urlOfYourMongoDatabase'
Then upgrade your db.js like this:
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/TodoApp', { useNewUrlParser: true })
.then(connect => console.log('connected to mongodb..'))
.catch(e => console.log('could not connect to mongodb', e))
module.exports = {mongoose}
Good luck!
Allow heroku ip access in mongodb by setting allow access from anywhere in network acess in mongodb.
this works,
but not sure how secured is it by allowing access from anywhere.
In 2021, navigate to your app in Heroku. Click on "Settings" menu. Once it opens expand "Config Vars" by clicking on it. Fill KEY and VALUE fields as it as in your .env file. Suppose you have DB_HOST=url/of/your/mongodb in your .env. The KEY will be DB_HOST and VALUE will be url/of/your/mongodb. Now click on ADD button. You are good to go.

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.

heroku db connection refused

I am pretty new to heroku and node. While I was trying to connect to heroku db, the following error shows up.
Error: connect ECONNREFUSED 127.0.0.1:5432
I am using connection pooling:
var pg = require('pg');
var heroconfig =process.env.DATABASE_URL || "postgres://jykyslkwkdsvhz:3ba43ff7db0c8dv9a914bac02f55ce944d8ccec31b67f858df3a858faa386c8e#ec2-54-243-214-198.compute-1.amazonaws.com:5432/dfiijlh3fbe3g9";
//var pool1 = new Pool(heroconfig);
var pool1 = new Pool(heroconfig);
app.get('/db', function(req, res){
pool1.query('SELECT * FROM test_table;',function(err, result){
if(err){
res.status(500).send(err.toString());
} else{
res.send(JSON.stringify(result.rows));
}
});
});
I tried to look at similar questions form other users but could not find solution involving pooling.
Please help.
I figured it out partially,
Storing the configuration data as object as below makes it works
var heroconfig = {
user: 'username',
database: 'database name',
password: 'some pass word',
host: 'host name',
port: 5432,
max: 10,
idleTimeoutMillis: 30000,
};
However while using the line of code mentioned in my original question, where database url is stored into the variable, it is not working:
var heroconfig =process.env.DATABASE_URL || "postgres://jykyslkwkdsvhz:3ba43ff7db0c8dv9a914bac02f55ce944d8ccec31b67f858df3a858faa386c8e#ec2-54-243-214-198.compute-1.amazonaws.com:5432/dfiijlh3fbe3g9";
I am planning to store my credentials in a different file and require it in my server file which seems to be a better approach.
I know this is late, but according to the docs in order to use a connection string, you must do this:
const { Pool, Client } = require('pg')
const connectionString = 'postgresql://dbuser:secretpassword#database.server.com:3211/mydb'
const pool = new Pool({
connectionString: connectionString,
})
See here: https://node-postgres.com/features/connecting#connection-uri
I have had such an error. After a lot of hours of research, I found out that my server deployed to Heroku was trying to access my PC PostgreSQL database. But it should have connected to the added-on PostgreSQL database in Heroku. I mean my server wasn't connecting to the database link in production mode, it was connecting to the database in development mode. I fixed it in my code like this.
db.js contents:
// focus on const environment
const environment = process.env.NODE_ENV || "development";
const knex = require("knex");
const knexfile = require("./knexfile");
const db = knex(knexfile[environment]);
module.exports = db;

Resources