简体   繁体   中英

How to best secure MongoDB database url in Node.js app

I have an API built on MongoDB and Node.js. In my app.js I have a database url that I need to include, with a password in the url. Is there a secure way to define this url as a variable in another file for when it is deployed? I will likely be using Heroku to deploy this.

app.js

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");

const product = require("./routes/product.route"); // Imports routes for the products
const app = express();

// Set up mongoose connection
const mongoose = require("mongoose");
// Change db url for new apps
let dev_db_url = "URL FOR MONGODB DATABASE TO BE SECURE";
const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));

由于您使用的是 Heroku,因此存储凭据的最佳方法是将它们定义为配置变量,然后可以从 Node.js 中的process.env访问它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM