VITE/React – Struggling to get environment variables to pick up my variables set in the “secrets” section of my terraform

  Kiến thức lập trình

I’m working with a React app using VITE (for the first time) and struggling to get the variables declared in my terraform (grabbed from AWS Parameter Store) to pull through. When I set the variable in a .env file like below and run locally, the variable is set fine as I can see in the console. However when I deploy it to our QA environment (Dockerized), the console logs it as undefined, using both process.env and import.meta.env. If anyone could shed some light on what I may be doing wrong and why I would appreciate it.

I’ve used both the VITE_ prefix and none to the env var with no success.

.env

VITE_TEST_URL=testurlworks

vite-env.d.ts

/// <reference types="vite/client" />

declare const VITE_TEST_URL: string;

Vite.config.ts

import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react-swc";
import dotenv from "dotenv";

dotenv.config();

export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };

  return defineConfig({
    plugins: [react()],
    define: {
      "process.env": process.env,
    },
    preview: {
      port: 80,
    },
    server: {
      port: 3000,
    },
  });
};

task.tf

locals {
  container_definitions = [
    {
      environment = [
        {
          name  = "ENVIRONMENT",
          value = terraform.workspace
        }
      ],
      secrets = [
        {
          "name": "VITE_TEST_URL",
          "valueFrom": "VALIDPATHTORESOURCE"
        }
      ]
    },
  ]
}

App.tsx

const testUrlProcessEnv = process.env.VITE_TEST_URL;
const testUrlImportMeta = import.meta.env.VITE_TEST_URL;

console.log("VITE_TEST_URL_PROCESS_ENV", testUrlProcessEnv);
console.log("VITE_TEST_URL_IMPORT_META", testUrlImportMeta);

Dockerfile

FROM node:22-alpine

RUN mkdir -p /app
WORKDIR /app

COPY . .

RUN npm install
RUN npm run build

EXPOSE 80
EXPOSE 3000

CMD ["npm", "run", "preview"]

I have a hunch this is an issue with VITE as we have other examples in the company of this concept working in Next.js so my last resort would be to convert this app to use Next, it’s fairly small so wouldn’t be too bad but obviously not ideal. I’m not sure if VITE is actually the issue or whether there is an issue in my config somewhere.

Note: I’ve changed var names and removed some code for security but if there is any more code you need to see let me know

New contributor

JoshWarbi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT