Vite/React & Node.js app can't read .env variables – Node.js

by
Ali Hasan
laravel-vite node.js reactjs

The Problem:

Unable to Access Environment Variables in Vite/React and Node.js Application

The Solutions:

Solution 1: Set Environment Variables with Consistent Prefix and Use dotenv-flow for Backend

  • Frontend (Vite/React):

    • Prefix environment variables with VITE_ to make them available in the frontend through import.meta.env.
    • Example: VITE_API_KEY = 'YOUR_API_KEY' in your .env file.
    • Access the variable in your React component using import.meta.env.VITE_API_KEY.
  • Backend (Node.js):

    • Install dotenv-flow package as a dependency (npm install dotenv-flow).
    • Add a scripts section to your package.json file with the following commands:
      • "start": "cross-env NODE_ENV=production node -r dotenv-flow/config index.mjs"
      • "dev": "cross-env NODE_ENV=development nodemon -r dotenv-flow/config"
    • These commands set the NODE_ENV environment variable and use dotenv-flow to load .env variables before running the Node.js server.
  • Additional Notes:

Q&A

Creating a full stack app with React – Node.js app can’t read .env variables

You need the VITE_ variable prefix in order to make it available to the import.meta.env: https://vitejs.dev/guide/env-and-mode.html#env-files

Video Explanation:

The following video, titled "Create React App Using Vite - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Welcome to this comprehensive tutorial on how to create a React app using Vite instead of the traditional Create React App (CRA) setup.