Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import API route in NextJS for getStaticProps?

I am using NextJS's getStaticProps to fetch some data from an external API. Reading the data fetching documentation on getStaticProps I came across this particular note:

Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach.

Right now I am calling getStaticProps directly from a page component called Index as follows:

export default function Index({ data }) {
  return <div>{data}</div>;
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/data");
  const data = await response.json();
  return { props: { data } };
}

As per the above documentation, this should not be done. How can I restructure my code to fetch data correctly? What does it mean to "import the API route and call its function yourself?"

like image 277
fredperk Avatar asked Sep 24 '20 06:09

fredperk


1 Answers

I think that the Note is related to internal api path

You should not use fetch() to call an API route in your application

I suppose is related to every path that you define in /pages/api/*. Instead of fetch you can simply refactor your code and import data.

So, the code below is correct, don't need any refactoring

export default function Index({ data }) {
  return <div>{data}</div>;
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/data");
  const data = await response.json();
  return { props: { data } };
}
like image 50
dna Avatar answered Oct 11 '22 12:10

dna