Harnessing the Power of dotenv in React with TypeScript

In modern web development, especially when working on React applications with TypeScript, managing environment variables is a crucial task. Environment variables are used to store configuration settings that can change based on the environment (e.g., development, testing, production). dotenv is a popular npm package that simplifies the process of loading environment variables from a .env file into a Node.js application. In this blog post, we will explore how to use dotenv in a React application written in TypeScript, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts
  2. Setting Up a React TypeScript Project with dotenv
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts

Environment Variables

Environment variables are key - value pairs that are used to configure an application. They can be used to store sensitive information such as API keys, database connection strings, or configuration settings that vary between different environments.

dotenv

dotenv is a zero - dependency module that loads environment variables from a .env file into process.env in a Node.js application. This allows you to keep your configuration settings separate from your codebase, making it easier to manage and deploy your application in different environments.

React and TypeScript

React is a popular JavaScript library for building user interfaces, and TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. When using React with TypeScript, we can take advantage of static typing to catch errors early in the development process.

Setting Up a React TypeScript Project with dotenv

Step 1: Create a new React TypeScript project

You can use create - react - app with the TypeScript template to create a new project:

npx create-react-app my-app --template typescript
cd my-app

Step 2: Install dotenv

Install the dotenv package using npm or yarn:

npm install dotenv

or

yarn add dotenv

Step 3: Create a .env file

Create a .env file in the root directory of your project. This file will contain your environment variables. For example:

REACT_APP_API_KEY=your_api_key
REACT_APP_API_URL=https://api.example.com

Note that in a React application, environment variables must start with REACT_APP_ to be available in the client - side code.

Usage Methods

Loading Environment Variables

In your TypeScript code, you can load the environment variables from the .env file using dotenv. In the src directory, you can create a file (e.g., env.ts) to load the variables:

import dotenv from 'dotenv';

dotenv.config();

export const API_KEY = process.env.REACT_APP_API_KEY;
export const API_URL = process.env.REACT_APP_API_URL;

Using Environment Variables in React Components

You can then use these environment variables in your React components. For example, in a functional component:

import React from 'react';
import { API_KEY, API_URL } from './env';

const App: React.FC = () => {
    return (
        <div>
            <p>API Key: {API_KEY}</p>
            <p>API URL: {API_URL}</p>
        </div>
    );
};

export default App;

Common Practices

Separating Environment Files

For different environments (development, production, testing), you can create separate .env files. For example, .env.development, .env.production, and .env.test. You can then specify which file to use based on the environment. In a Node.js script, you can do something like this:

import dotenv from 'dotenv';

const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env.development';
dotenv.config({ path: envFile });

Using TypeScript Types for Environment Variables

To avoid type errors when using environment variables, you can define types for them. For example:

interface EnvVars {
    REACT_APP_API_KEY: string;
    REACT_APP_API_URL: string;
}

const envVars: EnvVars = {
    REACT_APP_API_KEY: process.env.REACT_APP_API_KEY as string,
    REACT_APP_API_URL: process.env.REACT_APP_API_URL as string
};

export default envVars;

Best Practices

Security

  • Never commit the .env file to version control: The .env file may contain sensitive information such as API keys and database passwords. Add .env to your .gitignore file to prevent it from being committed.
  • Use Environment - Specific Variables: Make sure to use different environment variables for different environments to avoid exposing sensitive information in production.

Error Handling

  • Validate Environment Variables: Before using environment variables, validate that they are set. For example:
if (!process.env.REACT_APP_API_KEY) {
    throw new Error('REACT_APP_API_KEY is not set');
}

Configuration Management

  • Centralize Configuration: Keep all your environment variable loading and configuration in one place (e.g., a single env.ts file) to make it easier to manage and update.

Conclusion

Using dotenv in a React application with TypeScript is a powerful way to manage environment variables. It allows you to keep your configuration settings separate from your codebase, making your application more secure and easier to deploy in different environments. By following the common practices and best practices outlined in this blog post, you can effectively use dotenv in your React TypeScript projects.

References