Unable to connect to MongoDB upon deployment / production - javascript

My mongoDB connects just fine locally, then once I deploy to heroku, the connection URL becomes undefined. I have a .env file in my root directory, and a .gitignore which includes the .env. I need the mongo url to stay private, but I can only assume that this is why it shows as undefined in production...
Heres the error:
"MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string."
Heres my require:
require("dotenv").config()
var url = process.env.MONGODB_URI
Heres my connection:
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).catch(e => {
console.error(e.message)
})
Thanks in advance for the help.

Two things you need to do, Make that .env available for the production code, It can't access your local .env file.
Second is your mongo running on production ? mean availabe and accessible for the app through 27017 port ?
don't say it is running on your local machine.

You need to setup your variables where your app is deployed. It is not accessible from your .env file that you used while developing on your local host. If you deployed to heroku - here is a documentation of what to do. If it's not deployed to heroku, you can get an idea what to do next to make it work.

Related

How to hide my database string in a github public repo

I uploaded my repo and it has a database string named 'dbstring' which I do not want to share with anyone.
I created a repository secret on github and created a value named DBSTRING with its value but the thing is I dont know how to access it.
this is my uploaded code which reveals my dbstring.
const dbstring = mongodb+srv:/***********b.net
mongoose.connect(dbstring, { useUnifiedTopology: true, useNewUrlParser: true });
const db = mongoose.connection;
db.once('open', () => {
console.log('Database connected:', url);
});
How can I replace dbstring with secret value I created on my github repo?
What you need to do is to use Environment variables, where you can have a .env ( if you use dotenv ) for each environment. Then you keep your database credentials safe on your computer and on the server, this will also make it possible to target different environments like database production, dev, test, etc. Make sure you have .env file added in the .gitignore file.
It's also important that when you run this code it's executed on the server-side otherwise anyone with the dev tools open will be able to see the credentials as well. Then on your client side you make a request using axios to the URL related to that database connection.
If the ENV file works for you then what you can do is you can encrypt it before uploading it to the GitHub like creating an env-production file and encrypting it and once you use that repo you can decrypt it and you can also add that step to your CD/CI Line use this

MERN: 'Invalid API Key' Heroku Deployment?

How do I get Firebase Auth to work on Heroku Deployment?
Auth works in MERN app's local development without any issues. All private information is stored in an .env file and then called in my react app with process.env.VARIABLE_NAME.
However, when I deploy to Heroku production and add the env files as shown here, I get the error: "Your API key is invalid, please check you have copied it correctly"
This is my deployed Heroku app: https://evening-fortress-01391.herokuapp.com/login
REACT_APP_FIREBASE_API_KEY=XXXXXXXX
REACT_APP_FIREBASE_AUTH_DOMAIN=XXXXXXXX
REACT_APP_FIREBASE_PROJECT_ID=XXXXXXXX
REACT_APP_FIREBASE_STORAGE_BUCKET=XXXXXXXX
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=XXXXXXXX
REACT_APP_FIREBASE_APP_ID=XXXXXXXX
Also, running the command heroku config displays the inputted env variables in the terminal.
Any idea why Auth works locally but not in deployment? Thank you!
Answer because too long for a comment.
Sounds super hard to debug - also your app just shows a login and not the API key error =) To me it sounds like either just like it says, an incorrect API key or a formatting issue.
I would make a test config variable using the same characters as your API key like REACT_APP_FIREBASE_POTATO=p07470-test-example-foooobar and then in your frontend app just console.log("TEST" + process.env.REACT_APP_FIREBASE_POTATO);. Then publish that and check it in production.
This tests are the environment variables working at all and are there some character encoding issues (do you see the exact characters in the console as you should)

Express-session cause heroku app to throw internal server error

App was totally working locally however after deployment via heroku it started to throw internal server error. Just one time app worked via heroku and then again it started to give internal server error. Then i tried to find the source of error and i found the express-session is crashing my app when it is deployed via heroku.
Edit: App doesn't crash in the middle of the process, it doesn't totally work. No path is working. Every path throws internal server error because of express-session.
Server Codes
Sorry i forgot that i still have this question. I solved the issue. Problem was the session secret. I didn't realize that my .env file is in gitignore file and session was not taking secret from .env so i added a heroku config, named SECRET and that's the solution.

Heroku process.env.port is undefined

I am trying to run a node.js app on heroku. I got it working local, but when i deploy it on heroku i get the following error:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
This is the port i try to listen to:
const PORT = process.env.port || 3000;
When i logged what the process.env.port was it said process.env.port was undefined.
Is there anything i need to do to automatically set the port?
Edit (FIX):
So i found out where the problem was. The javascript was being minified, but the process.env.port was minified to something that didn't work. Thanks for the help.
for any one get to that post.
first check if you are writing process.env.PORT correctly.
I was writing .Port and it took 4 hours of my life to figure out the error
I had the same issue and found the solution to pass heroku dyno port variable to node start script.
If you have created a Procfile in your root directory of your project just open it.
If you haven't created a Procfile just go to root directory of your project and create a file called "Procfile". The file has no extension and it helps to heroku get the starter point of your application. More details about it: The Procfile
In Node.JS Heroku documentation there isn't provided any example how should look like Procfile.
In my case, I'm using Typescript and my output directory of .js files is in /build directory in my project folder. and I'm assuming that you have the same situation. If not, just put your starter file's directory.
Procfile:
web: PORT=$PORT node ./build/index.js
You should pass config args before run the server on heroku. In terminal type
$ heroku config:set PORT=3333
then you'll be able to get port number like this
const PORT = process.env.PORT || 3000;
If you assigned from terminal
console.log(PORT) => 3333
otherwise
console.log(PORT) => 3000
If you're using babel, do not use the babel plugin babel-plugin-transform-inline-environment-variables in Heroku.
I think Heroku does not set the PORT variable when doing a deployment, so that's why you would get undefined.
Just wanted to leave this for anybody who was confused like me, you have to use
process.env.PORT
NOT
process.env.$PORT

cannot start nodejs web api hosted in Azure

Learning nodejs and started to created my own restful API using restify.
I have created a very simple server.js file which contains basically a hello world type example starting up like:
server.post('/api/messages', servicemanager.verifyFramework(), servicemanager.listen());
server.get(/.*/, restify.serveStatic({
'directory': '.',
'default': 'index.html'
}));
server.listen(process.env.port || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
which works fine locally. I cant hit http://localhost:3978 and I can test my API calls just fine calling http://localhost:3978/api/messages.
I have deployed my code into bitbucket and now I want to host these APIs in Azure using App Services.
My project structure is like so:
/topfolder
-/myproject
-/node_modules
-/node_modules...
server.js
package.json
index.html
When I setup the new app service in Azure, I can see that the deployment receives the code from BB, but the service never responds to my requests.
I have setup the home path of the app to live in: /site/wwwroot/topfolder/myproject and I can see the index.html when I navigate to http://myproject.azurewebsites.net so thats good.
I actually get a 404 error:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
There are heaps of examples of how to setup continuous deployment using bitbucket and for the most part, they all seem to work, but my server.js file doesnt seem to be the getting called or starting up.
How can I debug whats going on here?
Is the packages.json file used in this scenario by Azure?
Thanks.
As the root directory path of the application hosted on Azure App Services, is D:\home\site\wwwroot. And about the nodejs application, the Azure fabric will find the entrance script in root directory like server.js. And the requests are handled via web.config in root directory. If there is missing server.js or web,config file, you will occur 404 error.
You can try to modify or your application's structure, like to:
-/node_modules
-/node_modules...
server.js
package.json
index.html
Then, you deploy your application to Azure via GIT or from BB, the Azure deployment task will run command npm install and generate the web.config wile in the root directory.
Any further concern, please feel free to let me know.

Categories