I use environmental vairables for my API endpoint (change between dev and production). So i set the variables in the UI i.e.
And then in my code:
axios
.post(
`${process.env.REACT_APP_API_URL}/getData`,
payload,
{
headers: {
"x-access-token": localStorage.getItem("token")
}
}
)
.then((res) => {
console.log("Response", res);
})
.catch((err) => {
console.log("Error", err);
});
However the site “crashes” with Uncaught ReferenceError: process is not defined
I know the [Support Guide] Using environment variables on Netlify correctly
But I don’t know how to transfer this to my problem.
@MR314159 The fact that the code you’ve supplied contains a reference to localStorage
makes me reasonably confident it’s your front-end code.
The process.env
and the Environment variables are for use during build time.
There is no process.env
available to the browser, as evidenced by the error you’re getting:
If it’s something which is a public key then you could access it during your build and ensure it is compiled into the build output as necessary.
If it’s supposed to be private, just note that nothing about using environment variables “protects them” on the front-end.
How can I do this. Is it a webpack.config.js or netlify.toml command?
@MR314159 I work with Webpack as little as is humanly possible so I cannot speak to its capabilities.
I know it’s not a “configuration setting” for the netlify.toml
.
The Netlify documentation for accessing environment variables is here:
https://docs.netlify.com/configure-builds/environment-variables/#access-variables
It links to this additional information for accessing variables after the build is complete:
https://docs.netlify.com/configure-builds/environment-variables/#use-variables-in-a-site-after-it-s-built
If the Netlify documentation doesn’t help, you could google around for a solution specific to your tech stack.