As you may see, I have my db connection file and another "protected" file, where my credentials are, and this file is included in .gitignore. I import it and reach the data. Quite basic. Therefore my questions are:
- Is this the right way to do it?
- If not, how should I do it? Plus: how could I add extra security to my account,connection?
- Let's suppose I have a private collection, that no one should see, how could I protect specially this collection? I mean, with a password or a two step verification let's say.
Current code:
const mongoose = require("mongoose");
const mongoCredentials = require("../protected/mongoCredential");
const URI = `mongodb+srv://${mongoCredentials.username}:${mongoCredential.password}
@firstcluster-eldi8.mongodb.net/culturapp?retryWrites=true&w=majority`;
mongoose.connect(URI, { useUnifiedTopology: true, useNewUrlParser: true })
.then(db => console.log("MongoDB is connected"))
.catch(err => console.log(">> ERROR: ",err));
module.exports = mongoose;
The correct way to do it is to use envrironmental variables.
Use environmental variables
Environmental variables are set on the environment, i.e your local development machine or the remote production server. Then, within your app, you read the environment variables and use them appropriately.
There's (at least) a couple reasons it's usually done like this:
Here's how you set environment variables (this is for Linux, other OS's might be different):
and here's how you read them within Node.js:
or pass variables to the process when starting up
Alternatively, you can pass variables when starting up the process like so:
However that's generally discouraged since you're most probably starting your process through the npm start script. Since
package.json
, where thenpm start
command is defined, is always committed to the repository it defeats the whole purpose of hiding the credentials.Like you mentioned along lines, using environment variables is more like security through obfuscation.
I would try to have the credentials in a separate configuration file. With a bit of design, encrypt this file and store those keys in secure enclaves or TPMs.
Check this thread.