Dynamic API URL Configuration in React - wwestlake/Labyrinth GitHub Wiki

Dynamic API URL Configuration in React

Objective

This technical specification outlines the procedure for configuring a dynamic API URL in a React application. The goal is to ensure that the application can automatically determine the appropriate API endpoint depending on the environment (development, staging, production).

Overview

To avoid hard-coding API URLs (e.g., localhost), we will implement a solution that dynamically sets the API URL based on environment variables. This ensures that the React app can be deployed in multiple environments while pointing to the correct backend API.

Key Components:

  1. Environment Variables
  2. Proxying in Development (Optional)
  3. Cloud Provider Settings
  4. Fallback Mechanisms

1. Environment Variables

1.1. Description

React uses environment variables to control various aspects of the app. We will use environment variables to define the API URL for different environments, such as development, staging, and production.

1.2. Steps to Implement

  1. Create Environment Variable Files: React supports environment variables stored in .env files. We will define three environment variable files:

    • .env.development
    • .env.production
    • .env.staging (optional, for staging environments)
  2. Define API URL in Each Environment File: In each environment file, define a variable that holds the API URL. React requires the environment variables to be prefixed with REACT_APP_.

    # .env.development
    REACT_APP_API_URL=http://localhost:5001/api
    
    # .env.production
    REACT_APP_API_URL=https://api.yourapp.com
    
    # .env.staging (optional)
    REACT_APP_API_URL=https://staging-api.yourapp.com
    
  3. Access Environment Variables in the Code: Use process.env.REACT_APP_API_URL to access the API URL in the application code.

    const API_BASE_URL = process.env.REACT_APP_API_URL;
    
    export const getPlugins = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/plugins`);
        return await response.json();
      } catch (error) {
        console.error('Error fetching plugins:', error);
      }
    };
    

2. Proxying in Development (Optional)

2.1. Description

During local development, React's development server can be configured to proxy API requests to the backend. This is useful if the API runs on a different port or domain.

2.2. Steps to Implement

  1. Configure Proxy in package.json: Add the proxy configuration to package.json to forward API requests to the backend during development.

    // package.json
    {
      "name": "my-app",
      "version": "0.1.0",
      "proxy": "http://localhost:5001"
    }
    
  2. Use Relative URLs in Development: When proxying, you can use relative URLs (e.g., /api/plugins) in your API calls, and React will automatically forward requests to the correct backend.

    export const getPlugins = async () => {
      try {
        const response = await fetch(`/api/plugins`);
        return await response.json();
      } catch (error) {
        console.error('Error fetching plugins:', error);
      }
    };
    

3. Cloud Provider Settings

3.1. Description

When deploying to a cloud provider like Netlify, Vercel, or Heroku, we can define environment variables directly through their respective dashboards. This allows the app to dynamically use the correct API URL for production, staging, or other environments.

3.2. Steps to Implement

  1. Access Environment Variables in the Cloud: Each cloud provider has a way to define environment variables:

    • Netlify: Go to Site settings > Build & deploy > Environment.
    • Vercel: Go to Settings > Environment Variables.
    • Heroku: Go to Settings > Config Vars.
  2. Define the API URL: Define the REACT_APP_API_URL variable in the cloud provider’s dashboard for each environment.

  3. Automatic Environment Detection: React will automatically use the appropriate environment variable (e.g., from .env.production or .env.staging) during build time, depending on the environment.


4. Fallback Mechanisms

4.1. Description

In case environment variables are missing, we can implement a fallback mechanism to ensure the app does not break.

4.2. Example of Fallback in Code

const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://default-api.yourapp.com';

export const getPlugins = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/plugins`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching plugins:', error);
  }
};

This ensures that if the environment variable is not set, the app defaults to a safe fallback API URL.


Conclusion

This approach ensures the React app can dynamically configure its API URL based on the environment it’s running in, whether during local development, staging, or production. By using environment variables, proxying in development, and cloud-based configuration, the app remains flexible, scalable, and secure for future deployments.