I am using dotenv to create an environment variable to insert a base url into my API call using react, dotenv, and webpack.
When I call the variables in the code, I don't get any error other than them printing as undefined. What am I doing wrong?
Here is my webpack file
const webpack = require("webpack");
const Dotenv = require("dotenv");
dotenv.config();
module.exports = (env) => {
return {
plugins: [
new Dotenv(),
new webpack.ProvidePlugin({
process: "process/browser",
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
],
};
};
Here are what the variables look like in the .env file in the root of my project
API_URL=http://localhost:8000
BASE_URL=https://my-url.com
And here is how I am accessing it in the code (with axios for auth)
axiosAuth: axios.create({
baseURL: `${process.env.BASE_URL}`,
timeout: 5000,
})
CodePudding user response:
Like Shah already explain, the only thing that you need is add the prefix "REACT_APP" to your current variables.. Change this:
API_URL=http://localhost:8000
BASE_URL=https://my-url.com
To this:
REACT_APP_API_URL=http://localhost:8000
REACT_APP_BASE_URL=https://my-url.com
CodePudding user response:
Set the values explicitly to be defined instead of the whole process.env
. Try:
new webpack.DefinePlugin({
'process.env': {
API_URL: JSON.stringify(process.env.API_URL),
BASE_URL: JSON.stringify(process.env.BASE_URL),
}
})
And if you're using create-react-app, prefixing REACT_APP_
will also work and you could remove the define plugin and Dotenv.
example:
API_URL -> REACT_APP_API_URL // .env
usage: `process.env.REACT_APP_API_URL