
Context
Right now, I’m developing a website, the Frontend is in React and the Backend is with Strapi.
During development, to make API calls for example, you can call the Backend through “localhost”, for instance.
But… in production, that’s not right, you have to use the actual domain.
When there are only a few pages, it’s not a problem, but when there are several, it can be annoying to have to manually change the URL on each page.
The advantage of an .env file is that it counts as an environment variable, meaning you define the domain once, then, whenever you need it on a page, you just fetch the variable you need. This way, you no longer need to search the code for the various domains, you just have to edit the .env, a big time saver.
Problem
When I tried to access the value from my .env file, it didn’t work.
Solution
To build my project, for the React part I used Vite.
Vite enforces a specific naming convention, meaning you can’t name variables just any way you like. For the variable to be picked up, its name must start with “VITE_”.
Example
I create an .env file at the root of the project, like this:

In this file, you can put something like:
VITE_DOMAIN_REACT=http://localhost:5174
Then, to get its value in React:
const DOMAIN_REACT = import.meta.env.VITE_DOMAIN_REACT;