I have a .env file in the root directory of a react vite project. Next to it I have two folders, one for an index.js that is an express server and one that is a src folder for my front end components. In my App.jsx component, I can easily access an environment variable in that .env file with
import.meta.env.VITE_MY_API_KEY
. I don’t even need to import anything at the top of the component, it just works.
However, in my server/index.js file, it just doesn’t seem to recognize the environment variable I want.
I started off with my code in index.js looking like this:
import dotenv from "dotenv";
dotenv.config();
console.log(process.env);
This seems to print my actual computer system variables. Things like my PATH, HOME, things like that. So I try this, to try and see if I can log my variable: console.log(process.env.VITE_MY_API_KEY)
and I get undefined printed to the console.
Because this is a Vite project, I also tried it the Vite way. This way works on my frontend, but when I try either console.log(import.meta.env);
or console.log(import.meta.env.VITE_MY_API_KEY);
, I get undefined for both.
I’m expecting an API key to be printed to the console. What could be going on here?
la.bonds is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.