Vite TypeError: Cannot read properties of undefined (reading 'VITE_YOUTUBE_API_KEY')

52 views Asked by At

I'm getting this error when trying to read an Env Variable from the .env file.

Things to know: my .env is in the root directory, the variable is prefixed by VITE_, and I'm trying to import it doing const apiKey = import.meta.env.VITE_YOUTUBE_API_KEY;

I've scoured the web, but most of the answers were either "use VITE prefix" or "use import.meta.env". I also tried using loadEnv like this https://vitejs.dev/config/#using-environment-variables-in-config, but I get "process is not defined" at const env = loadEnv(mode, process.cwd(), '').

Here's my .env (I've also tried removing the quotes from the variables, same thing):

MONGODB_URI="mongodb+srv://USER:[email protected]/tutorialsApp?retryWrites=true&w=majority&appName=Cluster0"
JWT_SECRET="JWT_SECRET"
VITE_YOUTUBE_API_KEY="YOUTUBE_API_KEY"
VITE_CHANNEL_ID="CHANNEL_ID"
VITE_CLIENT_ID="CLIENT_ID"

Edit: here's my vite.config.js:

import { transformWithEsbuild, defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// Access import.meta.env directly
const appEnv = import.meta.env;

export default defineConfig({
  plugins: [
    {
      name: "treat-js-files-as-jsx",
      async transform(code, id) {
        if (!id.match(/src\/.*\.js$/)) return null;

        return transformWithEsbuild(code, id, {
          loader: "jsx",
          jsx: "automatic",
        });
      },
    },
    react(),
  ],
  optimizeDeps: {
    force: true,
    esbuildOptions: {
      loader: {
        ".js": "jsx",
      },
    },
  },
  define: {
    __APP_ENV__: JSON.stringify(appEnv),
  },
});

Any help would be appreciated!

0

There are 0 answers