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.
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