Home Blogs .env file in React js

.env file in React js

by Anup Maurya
10 minutes read
.env file in React js

In a React.js project, the .env file is typically used to store environment variables. Environment variables are used to configure various aspects of your application, such as API keys, database connections, and other settings that may change between development and production environments. By keeping these values in a .env file. you can easily manage configuration for different environments and keep sensitive information secure & safe.

What are Environment Variables?

Environment variables are a fundamental component of development in ReactJS. They are variables that are defined outside of your application and can be used within your application. Consider them as invisible hands, delivering essential information to your applications in a secure, efficient, and organized manner.

Here’s how you can use a .env file in a React.js project

  1. Create an .env file: In the root directory of your React project, create a file named .env. You can create this file manually or by using a command-line tool.
  2. Define environment variables: In the .env file, you can define environment variables using the KEY=VALUE syntax.

Create environment variables

REACT_APP_API_KEY=your-api-key
REACT_APP_API_URL=your-api-url

Make sure to prefix your environment variable names with REACT_APP_ when working with React. This is a requirement to ensure that React can access these variables.

Access environment variables

You can access these environment variables in your JavaScript code by using process.env.

const apiKey = process.env.REACT_APP_API_KEY;
const apiUrl = process.env.REACT_APP_API_URL;


console.log(`API Key: ${apiKey}`);
console.log(`API URL: ${apiUrl}`);

Loading environment variables: Environment variables defined in the .env file will be automatically loaded when you start your React application using react-scripts (e.g., with npm start or yarn start). You don’t need to manually load the .env file in your code.

Please note that you should not commit your .env file to version control (e.g., Git) to keep sensitive information secure. You can include it in your .gitignore file to ensure it’s not accidentally committed.

Place the .env file outside of the src folder

related posts

Leave a Comment

Enable Notifications OK No thanks