Import.meta.env undefined on production build vitejs
Full error message
I am using Vite to statically compile my React app. However, after building, .env imports become undefined, which is not the case at the development stage.
Reading the docs, I've found out that these variables are replaced by their corresponding values, but upon looking at the source/compiled code in the DevTools after serving, it shows an empty object with the .env name/key.
My vite.config.ts configuration:
//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,
},
});
};
The code where I reference these .env vars:
//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,
};
};Solutionsource: stackoverflow \u2197
I just realized what the ViteJS documentation says and I'll leave it in case someone also suffers from this. To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/17e6f28545ff9629cf0ebf6180270a3b226afda538e2951a01e977d4cc82f038hash \u00b7 17e6f28545ff9629cf0ebf6180270a3b226afda538e2951a01e977d4cc82f038