1

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",
  });
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146

1 Answers1

1

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.

Edshav
  • 378
  • 1
  • 8
  • Fetch it from where the API route fetches it. Could you elaborate on this. – Mohammed Rehan Jun 30 '22 at 06:48
  • The API route doesn't fetch the data from an external file or api. The api endpoint returns a json object. I will attach that file for reference in the question. – Mohammed Rehan Jun 30 '22 at 07:58
  • You can move (copy/paste) the json into getData function UPD Or move it into a variable and use in the both places – Edshav Jun 30 '22 at 10:58
  • this guy seems to have no problem fetching localhost from `getStaticProps` https://www.youtube.com/watch?v=WrmndNpWSJw – suraj Jan 13 '23 at 14:37