在生产中,我的nextjs应用程序中的mongodb连接字符串出现了问题。我遵循了这个指南:https://www.mongodb.com/developer/how-to/nextjs-building-modern-applications/
我在这里读到了有关环境变量的内容:https://nextjs.org/docs/basic-features/environment-variables给了我这样一个想法,即我应该能够安全地将连接字符串存储为环境变量,而不需要将它暴露给浏览器,因为我只需要使用它服务器端?
当我在本地运行应用程序时,它运行得非常好。但是在生产(azure服务)中,除非我通过在变量中添加"NEXT_PUBLIC_“前缀向浏览器公开连接字符串,否则连接字符串似乎没有定义。
公开这个变量是否安全?我是否应该以不同的方式使其工作而不公开它/是否应该完全采用另一种方法?
我的database.js:
import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';
const client = new MongoClient(process.env.DB_CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function database(req, res, next) {
await client.connect();
req.dbClient = client;
req.db = client.db('Loggen');
return next();
}
const middleware = nextConnect();
middleware.use(database);
export default middleware;发布于 2022-01-06 16:36:24
不应公开env变量。
( A)在项目和.env.local中创建设置局部env变量文件。(通常忽略所有env文件:检查gitignore文件)
( B)定义维塞尔 .env变量(连接的值相同)
C)正如所讨论的这里,您应该遵循这示例,检查它们如何管理连接(这是一个官方示例),以避免连接重复和错误。
记住,您的.env变量只能访问服务器端。因此,如果您愿意,可以将它们转移到客户端,但不建议这样做。
您的database.js (例如: mongodb.js)应该是:
import { MongoClient } from 'mongodb';
const MONGODB_URI = process.env.mongoApiUrl;
const MONGODB_DB = process.env.MONGODB_DB;
// check the MongoDB URI
if (!MONGODB_URI) {
throw new Error('Define the MONGODB_URI environmental variable');
}
// check the MongoDB DB
if (!MONGODB_DB) {
throw new Error('Define the MONGODB_DB environmental variable');
}
let cachedClient = null;
let cachedDb = null;
export async function connectToDatabase() {
// check the cached.
if (cachedClient && cachedDb) {
// load from cache
return {
client: cachedClient,
db: cachedDb,
};
}
// set the connection options
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
// Connect to cluster
let client = new MongoClient(MONGODB_URI, opts);
await client.connect();
let db = client.db(MONGODB_DB);
// set cache
cachedClient = client;
cachedDb = db;
return {
client: cachedClient,
db: cachedDb,
};
}最好不要在next-connect中使用您的方法,它会创建大量的连接。
https://stackoverflow.com/questions/70606714
复制相似问题