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.
Edit: adding API endpoint
file: api/cs
export default async function handler(req, res) {
res.status(200).json({
headerText:
"Page Header text",
joinText:
"Some text",
benefits: [
{
src: "/cs/photo-1.webp",
text: "Some text",
},
{
src: "/cs/photo-2.webp",
text: "some text",
},
],
advisor: {
name: "Name",
email: "person-email",
linkedin: "https://www.linkedin.com/in/person",
},
advisorMsg:
"Some text",
});
}