Create-React-App .env file directory location (Non-root)

Viewed 3546

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.

1 Answers

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
Related