5

I'm trying to access environment variables at runtime in a Vue 3 application. I'm using vitejs for bundling.

the application is deployed on AKS, and values are stored as Kubernetes secrets.

I followed the instructions here and here

I have a .env file that contains the env varibles I want to expose:

VITE_OKTA_CLIENT=$VITE_OKTA_CLIENT
VITE_OKTA_ISSUER=$VITE_OKTA_ISSUER

$VITE_OKTA_ISSUER is the env variable in my k8s pod with the actual value.

and I try to use the variables like this:

import.meta.env.VITE_OKTA_CLIENT
import.meta.env.VITE_OKTA_ISSUER

the value from the imports are undefined

this is what my vitejs config looks like:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueI18n from '@intlify/vite-plugin-vue-i18n'
const path = require('path')

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, '/src'),
      '@okta/okta-auth-js': '@okta/okta-auth-js/dist/okta-auth-js.umd.js'
    }
  },
  optimizeDeps: {
    include: [
      '@vue/apollo-composable'
    ]
  },
  plugins: [
    vue(),
    vueI18n({
      include: path.resolve(__dirname, './src/locales/**')
    })
  ]
})

In my Kubernetes config files I'm referencing the env like this:

spec:
      containers:
      - name: webapp
        env:
          - name: VITE_ROUTER_BASE
            value: /
          - name: VITE_OKTA_CLIENT
            valueFrom:
              secretKeyRef:
                name: testsecret
                key: VITE_OKTA_CLIENT
          - name: VITE_OKTA_ISSUER
            valueFrom:
              secretKeyRef:
                name: testsecret
                key: VITE_OKTA_ISSUER

Is my configuration missing anything? or is there a better way to do this?

capiono
  • 2,875
  • 10
  • 40
  • 76
  • The environment variables are statically replaced during the production build, so "runtime environment variables" isn't possible with the `.env` files. Technically, you could build your app in a container, where you configure the env, and then deploy the result. However, the values would be built into the app, so they should not contain any sensitive info, but I'm guessing that's not the case based on your k8s config. – tony19 Apr 04 '21 at 05:02
  • Possibly this? https://stackoverflow.com/questions/66389043/how-can-i-use-vite-env-variables-in-vite-config-js/66389044#66389044 – Matt Apr 05 '21 at 09:01

0 Answers0