Today, I had one task to prevent unauthorised access of web application, so whenever a user will access the application on their browser, then that user must be authenticated, if not then we have to take it to the login page. To check whether the user is authenticated or not, we have a back-end API, where one end-point is dedicated for checking user authentication. That API accept JWT token and validate it, and return either true or false.
I wrote the code in UI using Axios package to call the API end point for validation. But I need to specify the URL of my APIs and the URL was stored in .env file. Just like in any NodeJS application, I tried to access process.env to access the environment variable, but it failed as process was not identified. Why? Because I was using Vite. So, I had to read the base url from .env file, so I searched for it on Google, and the information that I found was to make some changes in Vite Configuration file and enter each property there to access it. I’m not going to talk about it as it got failed for me, and didn’t worked. Then I found another article where they mentioned that, you have to use VITE as prefix for your key in .env like VITE_BASE_URL where BASE_URL was my property name. By doing so, Vite will automatically pick the VITE prefixed keys and ignore others. To use that property in your code, you have to use import.meta.env.VITE_BASE_URL. So, I used the VITE keyword but it still returned me undefined. I couldn’t understand what’s wrong with it, I’m doing everything as said by the Vite documentation.
After researching for a bit, then I got to know that your .env file has to be present in same directory where your Vite Configuration file exist and this was my mistake. I was storing .env file in other directory or sub-directory from the vite configuration directory to be precise. That’s why Vite was not able to pick up environment variables for me. I changed the directory and it worked and I was able to test my code.
Summary
- Always add .env file in same directory as your Vite configuration file.
- Always prefix VITE keyword in your keys because Vite will pick only those keys which have VITE keyword as prefix and ignore others without VITE as prefix.
0 Comments