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

291
Visualizações
How to fetch data from Nextjs API route when build and deploy?

I am trying to deploy my nextjs web app to vercel.

When I deploy my site, I get this:

> Build error occurred
FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUSED 127.0.0.1:3000

Here I am fetching data on localhost:3000, it works when npm run dev. But now I want to build and deploy my project, I cannot fetch from localhost anymore, and I don't know my domain name yet. So how do I fetch data from my API route when vercel is building my site?

export const getStaticPaths = async () => {
  const res = await fetch("http://localhost:3000/api/products");
  const products = await res.json();

  const paths = products.map((product) => ({
    params: { productId: product.id },
  }));

  return {
    paths: paths,
    fallback: false,
  };
};

export const getStaticProps = async (context) => {
  const res = await fetch(
    `http://localhost:3000/api/products/${context.params.productId}`
  );
  const product = await res.json();

  return {
    props: {
      product,
    },
  };
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If frontend and backend are running/hosted on the same server/domain. you don't have to specify hostname it'll point to the same domain as the client.

export const getStaticPaths = async () => {
  const res = await fetch("/api/products");
  // something
};

OR

you can use env variables for the host. Create a .env file on a project root. https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

.env

NEXT_PUBLIC_ENV = development;

Component

export const getStaticPaths = async () => {
  const url =
    "development" === process.env.NEXT_PUBLIC_ENV
      ? "http://localhost:3000/api/products"
      : "https://example.com/api/products";
  const res = await fetch(url);
  // something
};
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