I'm fetching data in getStaticProps() in Next js and this works fine in local development but generates an error in next build as the server isn't available while in next build
FetchError: request to http://localhost:3000/api/cs failed,
reason: connect ECONNREFUSED 127.0.0.1:3000
After reading some discussions on GitHub, came to know that you cannot use fetch directly in getStaticProps. So I then separated the fetch logic into separate file and call the the function inside the getStaticProps. Here's the code..
export async function getStaticProps({ params }) {
const data = await getData(params.id);
return {
props: {
data,
},
};
}
export async function getStaticPaths() {
return {
paths: [
{ params: { id: "cs" } },
{ params: { id: "hyd" } },
{ params: { id: "cass" } },
],
fallback: false,
};
}
and the getData code is in another file
export async function getData(id){
const res = await fetch(`http://localhost:3000/api/${id}`)
const data = await res.json()
return data
}
This code works in local development, but generates errors while in next build that the connection is refused as the server isn't available while in build mode. So I made the server run in another terminal, but this generates an error on the WriteStream instance.
Error: EPERM: operation not permitted, open 'D:\next-project\next-website\.next\trace'
Emitted 'error' event on WriteStream instance at:
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'D:\\next-project\\next-website\\.next\\trace'
}
I can fetch the data from client side but wanted to try the getStaticProps as the no of pages are just 3. What's the correct way to fetch the local next API to build a static page.
Do Not Fetch an API Route from getStaticProps or getStaticPaths You should not fetch an API Route from getStaticProps or getStaticPaths. Instead, write your server-side code directly in getStaticProps or getStaticPaths (or call a helper function).
Here’s why: getStaticProps and getStaticPaths run only on the server-side and will never run on the client-side. Moreover, these functions will not be included in the JS bundle for the browser. That means you can write code such as direct database queries without sending them to browsers. Read the Writing Server-Side code documentation to learn more.
https://nextjs.org/learn/basics/api-routes/api-routes-details
So don't fetch data from the local API route in the getData function. Fetch it from where the API route fetches it.