In my Next.js project, I encountered an issue where fetching data in getStaticProps()
worked perfectly during local development but resulted in an error during next build
. The error indicated that the server was not available while executing next build
.
FetchError: request to http://localhost:3000/api/cs failed,
reason: connect ECONNREFUSED 127.0.0.1:3000
After researching on GitHub, I learned that using fetch directly in getStaticProps is not recommended. To address this issue, I refactored my code by moving the fetch logic into a separate file and calling the function inside the getStaticProps
method. Here's how the updated code looks:
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,
};
}
The actual fetch logic for getData
resides in another file:
export async function getData(id){
const res = await fetch(`http://localhost:3000/api/${id}`)
const data = await res.json()
return data
}
Although this code functions correctly in local development, it encounters errors during next build
due to the server being unavailable in build mode. To resolve this, I ran the server in a separate terminal, which led to an error with 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'
}
While I can successfully fetch data from the client side, I wanted to explore utilizing getStaticProps
as there are only a few pages in my project. What is the correct approach to fetch the local Next.js API for building 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",
});
}