Search code examples
reactjsnext.jsasync-awaitfetch-apiopenweathermap

Nextjs weather app trying to call api. Not sure what I'm doing wrong. I get unauthorized error


Am I doing the api handling right? Or is there something I'm missing? This was originally a create react app project and now I'm trying to migrate to nextjs so maybe I'm missing something with how api calls should be done. Let me know if I need to show any more of my code.

This is in a separate from the main program.

export default async function ApiHandler(location) {
  
  try{
       

    const data = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${location}&units=imperial&appid=${process.env.API_KEY}`
      );
  
    const res = await data.json();

    
    console.log(res.data);
    
      } catch (error){
          console.log("Error connecting to api");
          return new Response("Error in getting weather data", { status: 500 });
      }

}

Solution

  • In NextJs you need to use the NEXT_PUBLIC_ prefix on your env variable for them to be exposed in client components (assuming you are using a client component here)

    See the docs:

    https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser