DEV Community

Derek Nguyen
Derek Nguyen

Posted on • Edited on

3 3

'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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay