What's the best way to configure API endpoints in a React app for different environments?

Hey everyone! I’m pretty new to React and I’m trying to figure out how to handle API endpoints in my app. I’ve got a React frontend that I want to deploy on a cloud service like S3 or Google Storage. The tricky part is that it needs to talk to different API servers depending on whether it’s in dev, staging, or production.

I’m wondering what’s the best approach to set up these API URLs so I can easily switch between environments? Is there a way to do this without hardcoding the URLs?

I’ve been looking into environment variables, but I’m not sure if that’s the right way to go. Any tips or best practices would be super helpful!

Here’s a basic example of what I’m dealing with:

function fetchData() {
  const apiUrl = // What should go here?
  fetch(apiUrl)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
}

Thanks in advance for any advice!

hey there! i’ve found using a .env file for each environment works great. you can set up different files like .env.development, .env.staging, and .env.production. then in your code, you can access these vars like:

const apiUrl = process.env.REACT_APP_API_URL;

this way, you dont hardcode urls and can easily switch between envs. hope this helps!

One effective approach I’ve used for managing API endpoints across environments is to leverage environment variables in combination with a configuration file. Here’s how I typically set it up:

Create a config.js file in your src directory. In this file, define your API endpoints based on the current environment:

const env = process.env.REACT_APP_ENV || 'development';

const config = {
  development: {
    apiUrl: 'http://localhost:3000/api',
  },
  staging: {
    apiUrl: 'https://staging-api.example.com',
  },
  production: {
    apiUrl: 'https://api.example.com',
  },
};

export default config[env];

Then, in your React components or API service files, you can import and use this configuration:

import config from './config';

function fetchData() {
  fetch(`${config.apiUrl}/endpoint`)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
}

This approach allows you to easily switch between environments by setting the REACT_APP_ENV variable during your build process or deployment. It’s clean, maintainable, and doesn’t require hardcoding URLs in your code.

hmmm, interesting question! have you considered using a config file with a switch statement? something like:

const getApiUrl = () => {
  switch(process.env.NODE_ENV) {
    case 'development': return 'http://localhost:3000';
    case 'staging': return 'https://staging-api.example.com';
    default: return 'https://prod-api.example.com';
  }
}

this way you can easily add more environments too. what do you think?