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...
As I mentioned in the comments, the variable is being replaced by
{}.VITE_KEYbecause the variable was not found during yournpm run buildprocessi.e you only defined it for the development environment -
.env.local.What you can do:
.envto take care of both local and production environments, or.env.productionfile but ensure you add it to.gitignorefile so it does not get pushed to GitHub.i.e your
.gitginorefile should include this:That way, the
.env.productionfile 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_KEYin 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.