Working With Environment Variables in React

Working With Environment Variables in React

Sensitive data, such as a secret key retrieved from an external API, specific login credentials, or application settings that need to be protected, are frequently involved in the creation or deployment of websites. Environment variables provide an essential layer of protection and other advantages, as hardcoding these as variables into a website might be a significant security concern.

Outside of your code, environment variables typically have values in the form of key-value pairs. These values are kept locally in a file with the extension .env or on deployment platforms such as Vercel, AWS, Heroku, etc. and can be dynamically modified. They can be used as database connection URIs, secret/private keys, or API keys. It is imperative that developers comprehend the significance of these elements because:

  • Application security is one of the most important aspects of environment variables. Implementing specific values directly in an application exposes it to hackers, fraudsters, and other dangerous individuals, whether on the front end, in a mobile application, or in the backend. Consider environment variables such as passwords, which are extremely private and run the risk of being accessed by unauthorised parties should they get into possession of them.

  • Configuration management refers to the various settings or variables that occur during the development and deployment processes. Rather of rewriting the code to accommodate these changes, environment variables allow for dynamic changes to these settings and values, making configuration maintenance across the code easier.

  • Environment variables let a programme be more flexible and portable by allowing it to separate configuration information from code, which increases the application's adaptability in a variety of situations. Without requiring significant code changes, developers can retrieve the required information whenever they need it.

What’s “.env” file?

An environment file, abbreviated as ".env," is a plaintext configuration file that programmes utilise to control settings. Sensitive data and environment-specific variables are especially well-suited for its storage.

Here's a breakdown:

  1. Key-Value Pairs: In a ".env" file, configuration settings are stored as key-value pairs. For example:

     API_KEY=mySecretKey
     DATABASE_URL=example.com/db
    
  2. Environment Variables: The entries in the ".env" file become environment variables, accessible by the application. These variables can be used to control behavior or store sensitive data.

  3. Security: Sensitive information like API keys or database passwords is placed in the ".env" file, keeping it separate from the application code. This adds a layer of security, as the file is typically excluded from version control systems.

  4. Usage in Code: In code (for example, in a Node.js or Python application), you'd access these variables like this:

    • JavaScript (Node.js):

        const apiKey = process.env.API_KEY;
        const dbUrl = process.env.DATABASE_URL;
      
    • Python:

        import os
      
        api_key = os.environ.get('API_KEY')
        db_url = os.environ.get('DATABASE_URL')
      

These examples retrieve the values of API_KEY and DATABASE_URL from the environment variables.

  1. Environment-specific Configurations: ".env" files are often used to manage environment-specific configurations. For instance, you might have different database URLs for development and production environments.

Remember to keep ".env" files secure and never expose them publicly, as they can contain sensitive information critical to the security of your application.

Setup

Before delving into the specifics of utilizing a .env file in a React application, let's establish a foundational React project. If you haven't already, initiate a new React application using the following commands:

npx create-react-app dotenv-react-app
cd dotenv-react-app

At the root of your project, generate a .env file. Your application structure should resemble the following:

dotenv-react-app/
|-- node_modules/
|-- public/
|-- src/
|-- .env
|-- .gitignore
|-- package.json
|-- README.md

As illustrated, every React application includes a .gitignore file by default. Ensure that .env is either present or add it to .gitignore to prevent the exposure of environment variables on GitHub. The .gitignore content should appear as follows:

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

The .gitignore file indicates various types of .env files, each serving distinct purposes. These include:

  • env.local for environment-specific configurations on your computer.

  • .env.development and .env.production differentiate between development and production environments.

  • .env.example or .env.sample act as templates for required variables. While the commonly used one is .env, the choice of extension depends on specific framework or tool conventions. Developers should refer to documentation for guidance.

Using environment variables in the application:

It's crucial to restart your application if you modify any environment variable in the .env file to reflect changes. To access these variables in a React application, simply prefix the environment variable with process.env. Let's explore a practical example by fetching data from an API with a URL stored in the .env file:

REACT_APP_API_URL=https://api.example.com/data

import React, { useEffect, useState } from 'react';

const DataFetcher = () => {
 const [data, setData] = useState(null);

 useEffect(() => {
  // Fetch data from the API using the environment variable
  const fetchData = async () => {
   try {
    const response = await fetch(process.env.REACT_APP_API_URL);
    const result = await response.json();
    setData(result);
   } catch (error) {
    console.error('Error fetching data:', error);
   }
  };

  fetchData();
 }, []);
 // Rest of the component code...
};

In this example, REACT_APP_API_URL is the environment variable storing the API URL, accessed from the .env file using process.env.REACT_APP_API_URLThe variable can be changed during development or deployment, but always restart your application when updating any environment variable.

Conclusion

To sum up, using a.env file to include environment variables in a React application secures sensitive data and enhances the code's scalability and maintainability. By separating essential information like API URLs and keys in the .env file, developers dramatically limit the danger of unauthorised access. Protecting critical credentials is the top priority of this security measure, which is essential for both development and deployment. We stressed the value of environment variables throughout this post, providing a detailed tutorial on how to set up and use a dotenv file in a React application. Following these best practices makes React apps more flexible and secure while also guaranteeing a smooth development and deployment process.

Did you find this article valuable?

Support Twelve by becoming a sponsor. Any amount is appreciated!