Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

0

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; 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!