I have defined HOMEPAGE_URL=/home
in .env
.
I am using it in App.js
(I tried to call it both inside and outside function App()
.
...
const dotenv = require('dotenv')
dotenv.config()
import './App.css';
function App() {
const [data, setData] = useState({}); //initial value is an empty object
useEffect(() => {
fetch(HOMEPAGE_URL)
...
I created a test case in app.test.js
...
const dotenv = require('dotenv')
beforeAll(()=>{
dotenv.config()
})
...
describe("home page test cases", ()=>{
it('renders homepage content', async () => {
render(<App />);
expect(global.fetch).toHaveBeenCalledTimes(1)
expect(await screen.findByText("welcome")).toBeInTheDocument()
});
})
The test case fails with error
home page test cases › renders homepage content
ReferenceError: HOMEPAGE_URL is not defined
22 |
23 | useEffect(() => {
> 24 | fetch(HOMEPAGE_URL)
| ^
25 | .then((res) => {
26 | console.log(`got response: ${JSON.stringify(res)}`);
27 | return res.json(); //return json from res
Why is HOMEPAGE_URL
undefined?
4
Answers
I think is just define the environment constant like:
Above the fetch function and it will work.
The
dotenv
just work like an environment file control, and will select the.env
file you set on cli command but to access this variable, you still need to use ‘process.env.(env name)’ in JavaScript.dotenv
package loads the variables defined in.env
intoprocess.env
.To access, you have to use
process.env.HOMEPAGE_URL
instead ofHOMEPAGE_URL
.Refer the NPM package: https://www.npmjs.com/package/dotenv?activeTab=readme#:~:text=Dotenv%20is%20a%20zero%2Ddependency%20module%20that%20loads%20environment%20variables%20from%20a%20.env%20file%20into%20process.env.
If you using Vite, this is from the documentation Docs
To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code. e.g. for the following env variables:
Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY to your client source code, but DB_PASSWORD will not.
When using Create-React-App, it’s essential to prefix your environment variables with
REACT_APP_
. Failure to do so will result in the variables not being injected. SourceIf you’re using VITE, ensure that your variables are prefixed with
VITE_
. Keep in mind that this configuration can be customized via thevite.config
file. SourceIn both cases, the
.env
file is parsed automatically (dotenv not required). For example,HOMEPAGE_URL
won’t work as expected; it must be prefixed accordingly, such asREACT_APP_HOMEPAGE_URL
.This is crucial because file building is an OS-level operation, and it grants access to all environment variables. Among these variables, there may be sensitive data. React’s approach is to filter out data that should be incorporated into the built script, as the built script is public and visible to everyone, and sensitive data cannot be injected.