Hello im trying to use environment at my MongoDB connection, but the value comes "undefined"
My database connection structure like:
src/db/connection.js
src/server.js
I can use console.log(process.env.MONGODB_URI)
at src/pages/index.js
but i cant use at backend server it says "undefined".
import mongoose from 'mongoose';
export const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
Next.JS version: 15.0.3
2
Answers
I hope my solution solves the issue you faced.
By default, process.env variables in Next.js are only available in the client and server-side code executed by Next.js. However, in your backend server, you need to ensure the environment variables are properly loaded.
Please try to use a .env.local file in the root of your project to define your environment variables.
In Next.js, environment variables used in the client-side code must start with NEXT_PUBLIC_. However, this does not apply to server-side code, including your database connection.
Ensure you are not adding the NEXT_PUBLIC_ prefix to MONGODB_URI, as it is meant for server-side usage.
Thanks in advance.
I hope this solves your problem.
Thanks.
Good Luck!