Search code examples
reactjscreate-react-appdotenvreact-scripts

Managing Two .env Files (Development and Production) in a React Project


If I create two .env files, one named .env.development and the other .env.production, in the main directory and I add the following scripts to my package.json:

    "start": "NODE_ENV=development react-scripts start",
    "build": "NODE_ENV=production react-scripts build"

what happens when I run npm start and npm run build?

For npm start, I understand it will use .env.development, but for npm run build, will it exclusively use .env.production in the production environment? Or will it include all .env files from the main directory in the build?

Additionally, is it safe to store API keys in .env.development or should I avoid doing that?


Solution

  • No need to manually set NODE_ENV in your package.json scripts, as Webpack automatically manages it. In production, it exclusively uses .env.production, and the content of .env.development won't be included in the build folder. If the content of .env.development is sensitive, ensure not to push it to Git, and maintain it on your local machine for security.

    Add .env.development to .gitignore as follows:

    .env.development
    /coverage
    build
    npm-debug.log*
    yarn-debug.log*
    yarn-error.log*
    

    Keep in mind that if you haven't used customized env variables in your code, they won't appear in the build files.