'Import.meta.env undefined on production build vitejs

I am using vitejs to compile my react app statically, however after build .env imports become undefined which is not the case on development stage.

reading the docs I've found out that these variables are replace by their corresponding values, but upon looking at the source/compiled code in the dev tools after serving it shows an empty object with the env name/key

enter image description here

i might have a wrong configuration in vite.config.ts so here it is.

//vite.config.ts
import { defineConfig, loadEnv } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import { getAliases } from 'vite-aliases';

const aliases = getAliases({
  path: 'src',
  prefix: '@',
});

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

  // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
  // import.meta.env.VITE_PORT available here with: process.env.VITE_PORT

  const plugins = mode === 'development' ? [reactRefresh()] : [];
  return defineConfig({
    plugins,
    publicDir: 'src/assets',
    resolve: {
      alias: aliases,
    },
    build: {
      chunkSizeWarningLimit: 1500,
    },
  });
};

And also the code where I'm referencing these env var

//config.ts
export const config = () => {
  const url = import.meta.env.VITE_SERVER_URL;
  const api = import.meta.env.VITE_API_ENDPOINT;
  const auth = import.meta.env.VITE_AUTH_ENDPOINT;

  const isProd = import.meta.env.MODE === 'production';
  const isDev = import.meta.env.MODE === 'development';

  console.log(url, api, auth);
  return {
    api: (endpoint: string) => `${url}${api}${endpoint}`,
    auth: (endpoint: string) => `${url}${auth}${endpoint}`,
    test: (endpoint: string) => `${url}test${endpoint}`,
    isProd,
    isDev,
  };
};



Solution 1:[1]

I just realized what the ViteJS documentation says and I'll leave it in case someone also suffers from this.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gerson Malca Bazan