When I use "npm run buid" with Vite, "import.meta.env." is replaced by {} in dist

867 Views Asked by At

I need to use a secret key for a fetch to an API. I work with Vite. I want to have my key available in development environment so I created a file env.development.local with my key :

VITE_KEY=myKey

and it works just fine in development : import.meta.env.VITE_KEY is replaced by myKey and I'm able to use it.

I didn't create a file env.production because I don't want to display my key publicly on gitHub, and so I don't want it to be in my Javascript file in the dist directory.

And I would like to declare an environment variable for production on Vercel or a secret action on github, with my VITE_KEY inside of it. But that doesn't work. And I noticed than when I run "npm run build" to bundle my files for distribution, import.meta.env.VITE_KEY is replaced by {}.VITE_KEY. Is that normal?

How can I do to declare and use this environment variable in production with an external service like vercel or github? I searched for hours but I can't find any answer for this problem...

1

There are 1 best solutions below

0
Airah On

As I mentioned in the comments, the variable is being replaced by {}.VITE_KEY because the variable was not found during your npm run build process

i.e you only defined it for the development environment - .env.local.

What you can do:

  1. use .env to take care of both local and production environments, or
  2. add a .env.production file but ensure you add it to .gitignore file so it does not get pushed to GitHub.

i.e your .gitginore file should include this:

#Ignore .env files
.env
.env.local
.env.production

That way, the .env.production file is also ignored.

As for Vercel, you also did not add enough details to debug, but ensure you are setting an environment variable for VITE_KEY in the deploy settings for the project.

I personally use Netlify and these work for React + Vite projects, but Vercel may have other settings, so check out this guide for more details.

One of these should resolve the issue, otherwise, you need to improve your questions with further details.