Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

784
Visualizações
Fetch data from local Next API in getStaticProps in Next js

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda