0

Please put me out of my misery. I see scores of other people had the same issue and I don't see a solution.

I am trying to put my sensitive keys into environment-specific files (.env.development, .env.staging, etc). The keys work fine if I put them in .env but I need this file for some other items which must be pushed up to source control. All of the files are in root (I see that this was a common mistake). Is there something with webpack that is the issue? I have restarted the server instance every time I make a change.

const express = require('express');
const path = require('path');
const app = express();
require('dotenv').config();

console.log('ENV', process.env.NODE_ENV);   // this returns "development"
console.log('Hello?', process.env.REACT_APP_HELLO);  // this returns "undefined"

As noted I am surfacing the environment correctly.

 "start": "SET NODE_ENV=development&& node server/index.js",

from package.json

REACT_APP_HELLO=BLAH

from .env.development

1 Answer 1

1

I assume you're in cmd.exe because of the set. Add a space before the &&: "start": "set NODE_ENV=development && node server", (no need to specify index.js. On non-Windows systems this would be NODE_ENV=development node server.

EDIT:

To get .env.development working, change the dotenv line to this: require('dotenv').config({ path: '.env.' + process.env.NODE_ENV }). (source), or the custom-env package: require('custom-env').env(process.env.NODE_ENV). Neither of those inherit from the regular .env though, so if you need that, check out dotenv-flow. I haven't tried the last package, but it seems to have the most features and the least amount of config to get working.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for the response! Actually I think you are wrong about the space - I had something fail separately recently because a space was added to the end of the variable. Anyway, I did try it - same result. Yes, I am on windows.
&& isn't part of the environment variable, it's an operator. It means "do the thing on the left, and if that doesn't fail, then do the thing on the right." But I see the other problem, I'll update my answer.
Right - I completely get that. What I am saying is that I did something similar recently where the resulting variable had a space in it when there was a space before the ampersand.
Thank you so much! That was exactly the problem! Incidentally I also tried it with the space before the ampersand - that absolutely broke it.
Bizarre, that's not what I would expect (but I also don't use Windows hardly ever, so there could be something I'm forgetting). Anyway I'm glad the env problem is sorted out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.