1

I'm creating a full stack app with vite/react and node.js I have to use an API key in my backend to interact with GPT but ofcourse, I want to use that in my .env file.

However, whatever I try, my backend reads the environment variable as undefined..

I've went on the internet to find solutions but nothing works so maybe there is like something new going on..

My .env file (Which is in the same path as my package.json)

REACT_APP_API_KEY ='HERE IS MY SECRET KEY'
// or //
VITE_API_KEY ='HERE IS MY SECRET KEY'

and in my server.js (Is in the same path as the .env file)

console.log(process.env.REACT_APP_API_KEY)
// or //
console.log(import.meta.env.VITE_API_KEY)

These both options return undefined..

I also want to mention that I do have the cross-env package installed. So I've absolutely no clue what Ï'm doing wrong..

  • Sometimes, restarting the IDE does the job. I have come into such problems and restarting does the job. I think it does help in reading the env file. I have done this in VS Code and it works. – Himanshu Verma Aug 02 '23 at 15:19
  • Unfortunately, this didn't work.. – Stef-Verniers Aug 02 '23 at 15:35
  • Does this answer your question? [How to load environment variables from .env file using Vite](https://stackoverflow.com/questions/70709987/how-to-load-environment-variables-from-env-file-using-vite) – Phil Aug 03 '23 at 04:30
  • @Phil, sorry for the late reply. I've got it working but thanks for your answer! – Stef-Verniers Aug 03 '23 at 12:58

1 Answers1

1

for vite i am pretty sure you'll need the VITE_ variable prefix in order to make it available to the frontend over import.meta.env: https://vitejs.dev/guide/env-and-mode.html#env-files

on the other hand, backend node behaves differently, and does not offer .env support out of the box. i tend to use dotenv-flow for that, as a node preload script. something like this:

  "scripts": {
    "start": "cross-env NODE_ENV=production node -r dotenv-flow/config index.mjs",
    "dev": "cross-env NODE_ENV=development nodemon -r dotenv-flow/config ",
    "test": "cross-env NODE_ENV=test mocha -r dotenv-flow/config -r app/configs/_testhooks.mjs app/**/*.spec.mjs",
    "test:coverage": "c8 npm run test",
    "migrate:make": "knex migrate:make --knexfile app/configs/knexfile.cjs -x mjs -- ",
    "migrate:latest": "knex migrate:latest --knexfile app/configs/knexfile.cjs",
    "migrate:rollback": "knex migrate:rollback --knexfile app/configs/knexfile.cjs"
  },

If possible, please provide more details about your fullstack scenario, maybe there is other approaches more straightforward than those i presented.

update

you can see more details on the PR in the sample projet.

Sombriks
  • 3,370
  • 4
  • 34
  • 54