skip to Main Content

I’m writing a node script to build a custom web.config file in a react app for deployment. When I run it, I want it to read in .env variables. But when I do, I get undefined for the vars. It seems to be reading in global vars fine, but not the local .env. My script is in a folder in the root project folder. How do I pull those .env variables?

3

Answers


  1. Chosen as BEST ANSWER

    It looks like if I run my powershell command from the root folder it finds the .env file and reads it. I was running it from the folder I had the script in.


  2. If you’re using bash or zsh to run the script, you can do the following :

    source .env && node index.js
    
    Login or Signup to reply.
  3. First, make .env file:

    API_KEY = "5545f8g4:sa5h8f54d587eh8t545df5g"
    

    then install dotenv on your project:

    npm i dotenv
    

    then require it in your code:

    require('dotenv').config()
    

    then use it like that:

    console.log(process.env.API_KEY)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search