'How to use a third-party API inside next/api?

I am new to NEXTJS and creating a weather application .I am using a openweather api but how can I use it inside the next/api. I had tried by creating a file today.js inside next/api and wrote the code it in this way but I am unable to get data in console ?

today.js

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fecthInfo = async() => {
    const response = await fetch(url);
    const data = await response.json() ;
    return data;
}
export default function handler(req, res) {
    const result = fecthInfo();
    console.log(result)
    res.status(200).json(result)
  }

Can you tell the mistake I am doing , or I have to simply use the fetch method in any component like in reactJS.



Solution 1:[1]

Looks like you are missing an async/await. This should work:

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fetchInfo = async() => {
    const response = await fetch(url);
    const data = await response.json();
    return data;
};

export default async function handler(req, res) {
    const result = await fetchInfo();
    console.log(result);
    res.status(200).json(result);
}

Solution 2:[2]

Instead of fetching data from a remote api inside the api route. I suggest to use the getServerSideProps() in the route page directly so you have to fetch the data just once.

You pass the requested data through props to the Test component.

const Test= function({data}){
 console.log(data)
 return <div></div>
}



export default async function 
getServerSideProps(){
const response = await fetch(url);
const data = await response.json();
 return {
  props:{data}
 }
}

 export default Test; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remidy
Solution 2 Hamza Sehouli