3

After creating a new web app with create-react-app (CRA), I need to include some environment files for configuring various endpoints. Noticed that CRA comes with the cool dotenv package all ready to go. There's only one problem with that - I would like to have dotenv read these files from within my ./environments directory and not the root directory. Is there any way to load the .env, .env.local, .env.test, etc... files in a directory separate from the root directory?

Noticing I can achieve this in my express backend server.js by simply importing like so:

require('dotenv').config({ path: `./environments/` })

Can I do the same with my client-side code in React? If so, where should I put this import? Doesn't seem to work for me.

heyitsalec
  • 192
  • 4
  • 19

1 Answers1

6

If you created your project using CRA and want to configure dotenv to change the path from where it loads the env files, you will have to do npm eject.

Alternatively, you can use env-cmd to achieve the same:

Installation:

npm i env-cmd

Add scripts in package.json, for example:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    
    "dev": "env-cmd -f envs/.env.dev react-scripts build",
     "qa": "env-cmd -f envs/.env.qa react-scripts build",
    "demo": "env-cmd -f envs/.env.demo react-scripts build"
  },

After creating .env.dev, .env.qa, .env.demo in envs/ directory.

Now, you can run:

$ npm run dev // it will use envs/.env.dev file
$ npm run qa // it will use envs/.env.qa file
$ npm run demo // it will use envs/.env.demo file
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
  • 1
    Correct, see: https://github.com/facebook/create-react-app/blob/fddce8a9e21bf68f37054586deb0c8636a45f50b/packages/react-scripts/config/paths.js#L86 For the hard-coded .env path relative to the package root. This is not going to change by the looks of things https://github.com/facebook/create-react-app/issues/1697 Which is a shame as react-scripts is essentially zero configuration for loading .envs in compound order – kmjb Apr 21 '21 at 13:35