Dockerized React app facing CORS issues with RapidAPI

I’m stuck with a CORS problem in my React app. It was fine on my local machine, but now it’s giving me headaches in Docker. I’ve got it running on port 3003, and I’m trying to fetch data from a keto diet API. Here’s the error I’m seeing:

Access to XMLHttpRequest blocked by CORS policy: The 'Access-Control-Allow-Origin' header value 'http://localhost:3000' doesn't match the origin 'http://localhost:3003'.

My code looks something like this:

const apiConfig = {
  method: 'GET',
  url: 'https://keto-recipes-api.example.com/',
  params: {
    minProtein: '5',
    maxProtein: '15'
  },
  headers: {
    'API-Key': 'mysecretapikey',
    'API-Host': 'keto-recipes-api.example.com',
  },
};

function RecipeList() {
  const [recipes, setRecipes] = useState([]);

  const fetchRecipes = async () => {
    const result = await axios.request(apiConfig);
    setRecipes(result.data);
  };

  useEffect(() => {
    fetchRecipes();
  }, []);

  // Rest of the component...
}

Any ideas on how to fix this CORS issue in my Docker setup? I’m really scratching my head here. Help would be much appreciated!

This CORS issue is likely due to the API server not recognizing your Docker container’s origin. One effective approach is to use a reverse proxy like Nginx. You can set up Nginx in your Docker environment and configure it to proxy requests to the API while adding the necessary CORS headers. Then, update your React app to send requests to the Nginx proxy instead of directly to the API. Adjust your Docker network settings to ensure proper communication between the React container and the Nginx container. This solution has worked well in similar scenarios.

I’ve run into similar CORS issues when containerizing React apps. The problem stems from the mismatch between the API’s allowed origin (localhost:3000) and your Docker container’s address (localhost:3003).

Here’s what worked for me:

  1. Update your Dockerfile to set an environment variable for the API URL:
    ENV REACT_APP_API_URL=http://host.docker.internal:3003

  2. In your React app, use this environment variable instead of hardcoding the URL:
    const apiUrl = process.env.REACT_APP_API_URL || ‘http://localhost:3000’;

  3. Modify your Docker run command to include:
    –add-host=host.docker.internal:host-gateway

This setup allows your containerized app to communicate with the host machine’s network.

If that doesn’t solve it, you might need to configure CORS on the API side to accept requests from localhost:3003. Hope this helps!

hey TomDream42, sounds like ur having a rough time with cors. have u tried using a cors proxy? theres this neat one called ‘cors-anywhere’ that might help. just add https://cors-anywhere.herokuapp.com/ before ur api url. it could solve ur problem without changing ur docker setup. good luck!