I'm having a problem with my mongodb connection string in my nextjs CRUD application in production. I followed this guide: https://www.mongodb.com/developer/how-to/nextjs-building-modern-applications/
And I read about environment variables here: https://nextjs.org/docs/basic-features/environment-variables Giving me the idea that I should be able to safely store my connection string as an environment variable without exposing it to the browser, given I should only need to use it server side?
It works perfectly fine when I run the application locally. But in production (azure app service) the connection string appears undefined unless I expose it to the browser by adding the "NEXT_PUBLIC_" prefix to the variable.
Is it safe to expose this variable / Is there something I should do differently to make it work without exposing it / Is there another approach that should be taken entirely?
My 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;