3

I'm using ViteJS with React-ts template and i want to make deploy in Vercel using environment variables, locally i use "import.meta.env.VITE_XXX" and it works with my file .env, but when the application has ben deployed in the Vercel it doesn't works (I'm declared the environment variable in the Vercel configs), follow the example of use at environment variable in my code locally.

const urlApi = import.meta.env.VITE_VERCEL_XXX

When i run in localhost the value is equal my .env file When i run in Vercel the value is undefined

I read the docs of vite and vercel, but didn't found the solution

I'm expecting another resolution or one direction to resolve the problem

3 Answers3

0

I wonder what value you have set for local. In my case, the path is set to root, i.e. localhost:3000. This path is set automatically from node env by default. If I deploy the application to the server and the address is no longer root (i.e. "google.com/"), but is in some other nested folder, I have to set "PUBLIC_URL" in the .env where the entire server address is to the root of the application, for example. "https://www.server.com/app/dev/".

  1. I use a custom .env file to set the PUBLIC_URL .env.develop
VITE_VERSION=dev
PUBLIC_URL=https://server.com/myproject/develop/stats/app/
  1. It is also necessary to set the base url in vite.config.ts In the configuration, this is the "base" property
export default defineConfig({
  envDir: './buildConfig/environments',
  plugins: [react()],
  base: process.env.PUBLIC_URL,
  build: { outDir: process.env.BUILD_PATH },
});
  1. Also, is it possible that the build is not reading the correct .env file? If I have created my own file, I define the path to it using envDir, see above. and during the build I define the mode parameter in the script. for example, to build a develop environment with an .env.develop file, it would be vite --mode develop build vite will then take this .env.

Hopefully at least something will lead to success

Tom Trnka
  • 56
  • 4
0

In your Vercel Project settings, you have to add the exact same values as in your .env file:

key: VITE_YOUR-KEY value: yourApiKey

Then check the environments you want your variables to be used (Production, Preview and/or​ Development)

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 24 '23 at 01:27
0

The environment file needs to be in the application folder, in the root of the project it doesn't work i have this example in github https://github.com/hanspoo/vite-env-react-demo.

Hans Poo
  • 804
  • 1
  • 8
  • 17