"process is not defined" when used in a function (Vue/Quasar)

Viewed 911

The following snippet represents a Pinia store in my Vue 3 / Quasar 2 application. This store uses the environment variable VUE_APP_BACKEND_API_URL which shall be read from either the window object or process.env.

However I don't understand why the first variant is wokring but the second is not. Using the getEnv function always results in a Uncaught (in promise) ReferenceError: process is not defined error.

import { defineStore } from 'pinia';

function getEnv(name) {
  return window?.appConfig?.[name] || process.env[name];
}

// 1. this is working
const backendApiUrl = window?.appConfig?.VUE_APP_BACKEND_API_URL || process.env.VUE_APP_BACKEND_API_URL;

// 2. this is NOT working
const backendApiUrl = getEnv('VUE_APP_BACKEND_API_URL');

export const useAppConfigStore = defineStore('appConfig', {
  state: () => ({
    authorizationUrl: new URL(
      '/oauth2/authorization/keycloak',
      backendApiUrl,
    ).toString(),
    logoutUrl: new URL('/logout', backendApiUrl).toString(),
    backendApiUrl: new URL(backendApiUrl).toString(),
  }),
});
1 Answers

NodeJS-specific stuff like process doesn't exist in the browser environments. Both Webpack and Vite implementations work by replacing process.env.XYZ expressions with their values on build time. So, just process.env, or process.env[name] will not be replaced, which will lead to the errors you are experiencing. See the caveats section and related Webpack/Vite docs and resources. So, unfortunately, the only easy way seems to be the first long and repetitive way you've tried(const backendApiUrl = window?.appConfig?.VUE_APP_BACKEND_API_URL || process.env.VUE_APP_BACKEND_API_URL;). You can try embedding this logic in a single object, then use the function to access it.

const config = {
  VUE_APP_BACKEND_API_URL: window?.appConfig?.VUE_APP_BACKEND_API_URL || process.env.VUE_APP_BACKEND_API_URL
}

export function getEnv(name) {
  return config[name];
}

This way it will be longer and more repetitive to define it the first time, but at least you will be able to use it easily through the code base.

Related