skip to Main Content

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


  1. I think is just define the environment constant like:

    const HOMEPAGE_URL = process.env.HOMEPAGE_URL
    

    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.

    Login or Signup to reply.
  2. dotenv package loads the variables defined in .env into process.env.
    To access, you have to use process.env.HOMEPAGE_URL instead of HOMEPAGE_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.

    Login or Signup to reply.
  3. 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:

    VITE_SOME_KEY=123
    DB_PASSWORD=foobar
    

    Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY to your client source code, but DB_PASSWORD will not.

    console.log(import.meta.env.VITE_SOME_KEY) // 123
    console.log(import.meta.env.DB_PASSWORD) // undefined
    
    Login or Signup to reply.
  4. 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. Source

    If you’re using VITE, ensure that your variables are prefixed with VITE_. Keep in mind that this configuration can be customized via the vite.config file. Source

    In 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 as REACT_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search