reactjskubernetesvite

How to call a env variable in React VITE without the need of a .env


I'm currently trying to deploy a frontend app in a container in a kubernetes cluster, I have made a env variable named VITE_SERVER_ADDRESSS following the vite naming convention for environment variables. I have also checked if the pod containing this container has indeed the env variable. This environment variable is loaded from a config map.

Nonetheless, I am still not able to call this env variable in my frontend code which works locally but makes use of a .env file.

Due to the fact that this variables changes according to the environment, I need to use a configmap. Which with helm, allows me to change the VITE_SERVER_ADDRESS according to the environment.

This is the code for the frontend that calls the env variable

const serverAddress: string = import.meta.env.VITE_SERVER_ADDRESS;
console.log(import.meta.env.VITE_SERVER_ADDRESS);
const url: string = `http://${serverAddress}:8000/run-main`; //in the cluster I now have a undefined 

Solution

  • Ok, so I found a fix to the problem,

    The issue was with the fact that I needed to get the env variables *before *npm run build i.e build time. Me using a config map meant that I was getting the env variable in runtime and not build time. Instead with my original Dockerfile I was running npm run build which didn't have the environment variables due to the configmap.

    Instead in my helm template manifest files, I overrode the CMD in the Dockerfile with CMD and ARGS, and also utilized helms variables (e.g. {{.Values.env}})that changes according to the values.yml file with helm as shown bellow:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: project-ui-deployment
      namespace: {{.Values.namespace}}
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: project-ui-app
      template:
        metadata:
          labels:
            app: project-ui-app
        spec:
          containers:
            - name: project-ui
              image: {{.Values.ui_image}}
              ports:
                - containerPort: 3000
                  protocol: TCP
              env:
                - name: VITE_SERVER_ADDRESS
                  valueFrom:
                    configMapKeyRef:
                      name: project-configmap
                      key: VITE_SERVER_ADDRESS
    
              command: ["/bin/sh"]
              args:
                - "-c"
                - |
                  echo $VITE_SERVER_ADDRESS
                  export VITE_SERVER_ADDRESS=project-server-service{{.Values.env}}.project{{.Values.env}}.svc.cluster.local
                  npm run build
                  node server.js