DEV Community

Derek Nguyen
Derek Nguyen

Posted on • Edited on

'Ascending' server environment variables to client with Vite

TL;DR:

// vite.config.js
{
  envPrefix: ['VITE_', 'CF_PAGES_'],
}
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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}`
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

...but I haven't tried that, because I found this solution:

// vite.config.js
{
  envPrefix: ['VITE_', 'CF_PAGES_'],
}
Enter fullscreen mode Exit fullscreen mode

That would 'ascend' all the CF_PAGES_ variables & allow me to use them client side.

The end.

Top comments (0)