Reputation: 566
I am creating an app in React, MongoDB and Node.js and I am quite new. I am connecting to the MongoDB via Node in the following way:
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 8080;
const itemRoutes = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb+srv://my-database:somepassword-xposu.mongodb.net/collection?retryWrites=true&w=majority', { useNewUrlParser: true } )
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
});
I plan on deploying this app on Heroku, but this method of connection does not look very secure, I read about alternative ways, but could't find any, but I read that you can disable source mapping in an env file, but will that be enough to secure the app? If not then what is the secure way of connecting to MongoDB in your app and deploy it for production?
Upvotes: 1
Views: 924
Reputation: 1208
on Heroku you can add env vars which will be injected on your dyno to your app once deployed,for that you can use a lot of tools, for simplicity you can install the env2 from npm
, and create config.env
file on your app root directory and just call the vars from them for local use on the production you will be adding the same vars name on the Heroku environment and they will be injected so you will expect them to do so.
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const itemRoutes = express.Router();
require('env2')('config.env')
app.use(cors());
app.use(bodyParser.json());
const { DB_URL , PORT = 8080 } = process.env;
mongoose.connect(DB_URL, { useNewUrlParser: true } )
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
});
and on the config.env file just add this line
DB_URL = mongodb+srv://my-database:somepassword-xposu.mongodb.net/collection?retryWrites=true&w=majority
so on your local environment, your .env file exists so it will be injected to the node process and env variables and on the production, it will not exist on code base level rather than injected from the Heroku level
Note: make sure you add the
config.env
file to the `.gitignore' file
Upvotes: 1