Access to rawg api is blocked by CORS policy. While accessing resources after deploying application to vercel

Access to XMLHttpRequest at ‘https://api.rawg.io/api/games’ from origin ‘https://raw-game-clone.vercel.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

1 Like

Did you fix this? I think I’m having a similar problem…

Access to XMLHttpRequest at ‘https://api.rawg.io/api/games?key=xxxxx’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

No mam. I have not fixed it. I think this happen because of rawg api is not supporting cross origin request .

I’m wondering if maybe this happened because I didn’t quit running the localhost server when I was done coding each day. I ran npm run dev and left the server running overnight for multiple days instead of using ^C to quit. Maybe the network kept constantly sending API requests and caused me to run out of available requests.

I checked the Developer Info on rawg, where I originally got my API key, and it says the number of requests left for the period is -96 and it also gives a new reset date for when I can make more requests.

Hi @amberm31,

Please check the Effect hook whether put a second argument of an empty array that triggered this Effect only once after mounted, I encountered the issue too, but fixed it early (Yes I wondered just few minutes passed, but made so many calls that 2000 requests already gone.

Screen Shot 2023-08-21 at 5.51.25 pm

Thank you! I did end up finding and fixing this issue but I’m glad you mentioned it for anyone else who might need to see it.

Understanding the Problem:

You’re trying to fetch game data from https://api.rawg.io/api/games directly from your website at https://raw-game-clone.vercel.app. However, the browser is blocking this due to a security rule called CORS (Cross-Origin Resource Sharing). Think of CORS as a doorman that only lets certain guests in. Right now, the doorman isn’t letting your website access the game data.

The Solution:

To bypass this “doorman”, you can use a middleman, technically called a “proxy server”. This proxy server will talk to the game data site on behalf of your website, get the data, and then pass it back to your website.

Setting Up the Proxy Server (Step-by-Step Guide):

  1. Install Dependencies:
    If you haven’t already, install the necessary packages:

    npm install express axios cors
    
  2. Create the Server File:
    Create a file named server.js in the root of your project.

  3. Set Up the Server:
    In server.js, paste the following code:

    import express from 'express';
    import axios from 'axios';
    import cors from 'cors';
    
    const app = express();
    const port = 3000;
    
    app.use(cors());
    
    app.get('/api/:endpoint*', async (req, res) => {
      try {
        const endpoint = req.params.endpoint + (req.params[0] || '');
        const response = await axios.get(`https://api.rawg.io/api/${endpoint}`, {
          params: { ...req.query, key: process.env.VITE_GAMES_API_KEY },
        });
        res.json(response.data);
      } catch (error) {
        res.status(500).json({ error: `${error.message}` });
      }
    });
    
    app.listen(port, () => {
      console.log(`Server is running at http://localhost:${port}`);
    });
    
  4. Update Frontend Requests:
    In api-client.ts, change the baseURL to:

    baseURL: 'http://localhost:3000/api',
    
  5. Run the Server:
    In your terminal, navigate to your project directory and run:

    node server.js
    
  6. Test the Setup:
    With both your frontend and the proxy server running, you should be able to fetch game data without any CORS issues.

  7. Deployment:
    If you’re using Render for deployment:

    • Deploy the backend (proxy server) and the frontend separately.
    • In the production environment on Render, ensure you update the environment variables to match those in your .env file, especially your API key.
    • Once deployed, update the baseURL in api-client.ts to the online address of your proxy server.

By following these steps, you’ll have a working proxy server that helps your website fetch game data without any hiccups, and you’ll be ready for deployment on Render with the correct environment settings.

Issue resolved. On my side issue was that code is not able to access rawg api key when it is deployed on server. Because i am storing api key in environment variable. So I had to put api key in environment variable on vercel server. Now my deployed project able to access it, and it run smoothly.

For me the main problem was, that I set the key in env variable. But Vercel uses process.env and axios import.meta.env.

So I had to update the vite.config.ts
(don’t forget to put the “VITE_” prefix into the loadenv())

Change in the api-client.ts to: params: { key: process.env.VITE_API_KEY }.

Install: npm i --save-dev @types/node