Let me explain how .env is loaded
import dotenv from 'dotenv'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '.env') });
Here is a step-by-step explanation of what's happening in the code:
The dotenv package is imported at the beginning of the script.
The fileURLToPath() function is imported from the built-in url module. This function is used to convert the current file's URL (import.meta.url) to an absolute file path that can be used by path module.
The __filename variable is set to the absolute file path of the current file using the fileURLToPath() function.
The __dirname variable is set to the directory name of the __filename variable using the path.dirname() function from the built-in path module.
dotenv.config() function is called with an options object that specifies the path to the .env file. The path.join() function is used to join the __dirname variable and the .env filename to get the absolute path to the .env file. The dotenv.config() function then reads the contents of the .env file and adds the environment variables to the process.env object.
Then you can use it like this: process.env.MYENVVARIABLE
.envfiles aren't read in automatically, you have to use a library or custom code to do it for you. I recommend the library @pzaenger mentioned. If you just have environment variables out and about in your system, you can access them throughprocess.env.