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

186
Visualizações
React .env files display in console but not in fetch()

I have a react app created with create-react-app, I also have a .env in the root folder with REACT_APP_SERVER_URL.

In my localhost environment, everything works as expected but when I build and deploy to Firebase then I get the error SyntaxError: Unexpected token < in JSON at position 0.

In the method, if I output it to the console console.log(process.env.REACT_APP_SERVER_URL) then the url is written to the console and I can click it and go to the home page which is just a json response (for testing).

However, in the following code, I get the SyntaxError as above

fetch(`${process.env.REACT_APP_SERVER_URL}/`, {
mode:"cors",
credentials :"include",
method : "GET",
headers : {
   Accept : "application/json",
   "Content-Type"  :"application/json"
   }
})
.then(response => response.json())
.then(data => {
     setHello(data.message)
     console.log(data.message)
})
.catch(er => {
     console.log("fetch was caught")
     console.log(er)
})

If Iconsole.log(process.env) then I can see the object with the correct value for the server url and if i replace the url in the fetch from the .env variable to hardcoded url (exact same as what gets printed to the console eg https://serverapi.com/) then everything works as expected again, and I see the data.message.

I've tried something like const {REACT_APP_SERVER_URL} = process.env but that didn't work either.

I'm running out of ideas as to why I get the error with the environment variable.

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

0

It clicked as I was typing this but in my .env file I had REACT_APP_SERVER_URL=https://server.com/ then in the fetch I had fetch(`${process.env.REACT_APP_SERVER_URL}/`) So because I had a / at the end of the SERVER_URL line and also in the fetch call then the final code had two // and looked like https://server.com// which was the issue. I fixed this by removing the / in the .env file

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