Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vite env variable returns undefined in production with vercel

Vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
});

and this is .env file:

VITE_API_KEY = "someKey"
VITE_API_BASE_URL = "baseurl"

I use the variables in my project like this:

const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const key = import.meta.env.VITE_API_KEY;
console.log(BASE_URL , key)

This works well on my localhost but when I deploy the project on Vercel the app breaks and console.log(BASE_URL, key) gives me undefined undefined. any idea? it's my first project on Vite and I have explored some similar questions but didn't resolve my problem

like image 886
amir_70 Avatar asked Sep 15 '25 08:09

amir_70


1 Answers

My solution was to define them inside the definedConfig function in the vite. config.ts file Something like

export default defineConfig({
  plugins: [react()],
  define: {
    "process.env": process.env,
    ENV_KEY: process.env.ENV_KEY,
  },
});

And I can now use it

someObj: {
  key: import.meta.env.ENV_KEY,
},

I am not completely sure if it is necessary to define the process.env within the function

  • https://vercel.com/docs/frameworks/vite#environment-variables
  • https://vitejs.dev/config/#using-environment-variables-in-config
like image 125
Luis Alvarez Avatar answered Sep 17 '25 22:09

Luis Alvarez