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?"
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 } };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With