skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. I hope this solves your problem.

    1. Check if the .env.local file is correctly located in the root.
    2. Use console.log(process.env) to debug which variables are available.
    3. Ensure dotenv is installed and correctly loaded if running outside Next.js.
    4. Ensure you are not adding the NEXT_PUBLIC_ prefix to MONGODB_URI, as it is meant for server-side usage.

    Thanks.
    Good Luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search