AdamCodes716
AdamCodes716

Reputation: 301

React environment variable not working in dev

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

Upvotes: 0

Views: 1370

Answers (1)

Zac Anger
Zac Anger

Reputation: 7747

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.

Upvotes: 1

Related Questions