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

204
Visualizações
How to avoid API duplication when fetching data with nextjs?

I have a route that I may call either from server side rendering, or from client:

export const getFooBar = async (): Promise<any> => {
  const res = await fetch(`/foo/bar`, {
    method: 'GET',
    headers: CONTENT_TYPE_JSON,
  })
  if (!res.ok) {
    //do something
  }
  //do something else
}

If I call this function from the server:

export const getServerSideProps: GetServerSideProps = async () => {
  getFooBar().then(() => {
    //do something
  })
}

I got an error on because it is not an absolute URL. Solution is to create another function with slightly different URI:

export const getFooBar = async (): Promise<any> => {
  const res = await fetch(`http://myapp/foo/bar`, {
    method: 'GET',
    headers: CONTENT_TYPE_JSON,
  })
  if (!res.ok) {
    //do something
  }
  //do something else
}

Or to pass a prefix URL argument in getFooBar.

But is there a more generic way to add the absolute URL part if it's coming from server side rendering?

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

0

The proxy you have set up in next.config.js is only relevant for client-side requests. For requests initiated on the server (like inside getServerSideProps) you should directly call the external API.

Given the APP_API environment variable is not exposed to the browser (it's not prefixed with NEXT_PUBLIC_), you could use that as a condition to either use the direct API endpoint on the server, or point to the proxy endpoint on the client.

export const getFooBar = async (): Promise<any> => {
    const url = process.env.APP_API ? `http://${process.env.APP_API}/bar` : '/foo/bar'
    const res = await fetch(url, {
        method: 'GET',
        headers: CONTENT_TYPE_JSON,
    })
    // Remaining code
}

Note that you could also use other conditions to verify if you're in the client or server, for example using typeof window === 'undefined'.

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