TL;DR:
// vite.config.js
{
  envPrefix: ['VITE_', 'CF_PAGES_'],
}
With Vite, we can set environment variables in a .env, .env.{mode}, or .env.{mode}.local:
SECRET_STUFF          = "only for server"
VITE_NOT_SECRET_STUFF = "for server and client"
The default VITE_ prefix will pass the variables to the client and we can use it with a string:
// in a client js file
let msg = `Hey {import.meta.env.VITE_NAME}`
But what if we want to 'ascend' an env set by the platform? In my case, I want to expose CF_PAGES_URL, which contains the preview url for my Cloudflare Pages build. Obviously I can't write it in .env... I have read somewhere that .env can access other variables with a syntax like
VITE_PAGES_URL=$CF_PAGES_URL
...but I haven't tried that, because I found this solution:
// vite.config.js
{
  envPrefix: ['VITE_', 'CF_PAGES_'],
}
That would 'ascend' all the CF_PAGES_ variables & allow me to use them client side.
The end.
 

 
    
Top comments (0)