skip to Main Content

I am trying to access my env variables saved in .env.local file in utils folder saved in root directory. It shows undefined when I console log it.

console.log({
    clientId: process.env.GOOGLE_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}); 

This is my folder structure-

enter image description here

3

Answers


  1. Chosen as BEST ANSWER

    Update: I moved my .env directory from utils folder to root directory and it worked for me.


  2. It is like the environment variables are not being properly loaded. Here are a few steps you can take to troubleshoot the issue:

    1. Check if you have properly installed the required packages to handle environment variables. Usually, dotenv package is used to load environment variables from a .env file. Make sure you have it installed by running:

      npm install dotenv
      
    2. Ensure that the .env.local file is in the correct location, which is the root directory of your project.

    3. Make sure you are calling the config() method from the dotenv package to load the environment variables before trying to access them. Place this code at the beginning of your application entry point (e.g., index.js, app.js, or server.js):

      require('dotenv').config();
      
    4. Check the spelling of the environment variables. Make sure they match exactly with the variable names in the .env.local file.

    5. Restart your application after making changes to the environment variables or their loading process.

    If you’ve followed these steps and still encounter issues, please double-check the .env.local file and verify that the environment variables are set correctly. If the problem persist reply to this answer.

    Login or Signup to reply.
  3. # To expose a public environment variable in Next.js, you have to prefix the environment variable with NEXT_PUBLIC

    Example:

    NEXT_PUBLIC_MYENVVARNAME="MYVALUE"
    

    You can use it like this:

    const myVal = process.env.NEXT_PUBLIC_MYENVVARNAME;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search