1

我在生产中的 nextjs CRUD 应用程序中的 mongodb 连接字符串有问题。我遵循了本指南:https ://www.mongodb.com/developer/how-to/nextjs-building-modern-applications/

我在这里阅读了有关环境变量的信息:https ://nextjs.org/docs/basic-features/environment-variables给了我一个想法,即我应该能够安全地将连接字符串存储为环境变量,而不会将其暴露给浏览器,鉴于我应该只需要在服务器端使用它?

当我在本地运行应用程序时,它工作得很好。但是在生产(天蓝色应用程序服务)中,连接字符串似乎未定义,除非我通过向变量添加“NEXT_PUBLIC_”前缀将其公开给浏览器。

公开这个变量是否安全/我是否应该做一些不同的事情以使其在不公开它的情况下工作/是否应该完全采用另一种方法?

我的数据库.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;
4

1 回答 1

0

您不应该公开env变量。

A).env.local在您的项目中创建文件并设置本地环境变量。(通常所有 env 文件都被忽略:检查gitignore文件)

B)您定义您的vercel .env变量(具有相同的连接值)

C) 正如这里所讨论的,你应该按照这个例子,检查他们是如何管理连接的(这是一个官方的例子),以避免连接重复和错误。

D)请记住,您的.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,它会创建大量的连接。

于 2022-01-06T16:36:24.460 回答