I have env var SERVER_URL=localhost:8000
config.js
export const SERVER_URL = process.env.SERVER_URL;
export { SERVER_URL as default };
and action:
function fetchData(apiUrl, timeout) {
return timeoutPromise(timeout || 15000, fetch(`${SERVER_URL}${apiUrl}`))
.then(checkHttpStatus)
.then(parseJSON);
}
but after use this fetchData
I get http://localhost:8000/undefined/some_api
idk where from came this undefined
I have env var SERVER_URL=localhost:8000
config.js
export const SERVER_URL = process.env.SERVER_URL;
export { SERVER_URL as default };
and action:
function fetchData(apiUrl, timeout) {
return timeoutPromise(timeout || 15000, fetch(`${SERVER_URL}${apiUrl}`))
.then(checkHttpStatus)
.then(parseJSON);
}
but after use this fetchData
I get http://localhost:8000/undefined/some_api
idk where from came this undefined
3 Answers
Reset to default 18If you are using create-react-app
, only environment variables prefixed with REACT_APP_
will be available.
Try console.log(SERVER_URL)
, that's where your undefined
came from.
Create an environment variable REACT_APP_SERVER_URL
instead and refer to it with process.env.REACT_APP_SERVER_URL
in your app.
Inside config.js
:
const SERVER_URL = process.env.SERVER_URL;
export default SERVER_URL;
Other file app.js
:
import SERVER_URL from './config';
I was having the same problem as OP and couldn't figure out why my env vars would't show up in react. For anyone coming from a nodejs background with little experience in react or create-react-app, this was a frustrating waste of hours for me that I'd like to save you!
Typically in nodejs I would import process
before trying to use it in a script, like this
import process from 'process';
...
console.log(process.env.MY_VAR);
but this is probably already happening under the hood with create-react-app and so if you reimport it (by simply importing it as shown above) for some reason (maybe it overrides the previous instance of process
?) it will wipe the env property clean and you wont be able to access anything.
The solution here is to not call import process
and just use the process object wherever you need. So literally anywhere you want just call something like
console.log(process.env.REACT_APP_MY_VAR);
I also tried importing dotenv which also for some reason would not work! You need to just get it out of the process object that already exists.
apiUrl
's value ? – Muhammad Usman Commented Apr 22, 2018 at 16:53some_api
– nitz Commented Apr 22, 2018 at 16:54