Search code examples
reactjshttp-status-code-404netlify

Site deploys fine on Netlify, but resources are failing to load


I have an issue, my website seems to build and deploy fine but when I visit it does not work. When I inspect element I receive error stating ‘Failed to load resource: the server responded with a status of 404 ()’. I understand that the page isn’t loading because it can’t be found but I don’t understand why it can’t be found, but the website is working fine locally.

website is build on react

Github: https://github.com/aff7n/weather-app

Website: https://profound-muffin-a078da.netlify.app/

I know all this may sound stupid, (bear with me since I'm a beginner with React) but how do I fix this?


Solution

  • You're using process.env in browsers to get the complete URL. This is your code:

    const apiUrl = `${process.env.REACT_APP_API_URL}/weather/?lat=${lat}&lon=${long}&units=metric&APPID=${process.env.REACT_APP_API_KEY}`;
    

    process is Node.js API, and it returns undefined in browsers. This is why, the URL is converted to:

    https://profound-muffin-a078da.netlify.app/undefined/weather/?lat=19.1981219&lon=72.9600269&units=metric&APPID=undefined
    

    The solution would be to:

    1. Hardcode the actual values of the variables. I don't see why you're using environment variables here. There's nothing sensitive in the URL, anyone can see it anyways.

    2. OR Refer to: https://create-react-app.dev/docs/adding-custom-environment-variables/. Quoting:

    You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

    Basically, prefix the variables with REACT_APP_. The end result would be same as option 1 though.

    1. Final option: Use Netlify Functions (or Netlify Edge Functions) to make a call to the API and return the response to the client application. Here, you can use process.env (or Deno.env if you use Netlify Edge Functions) and keep the URL a secret.