Frontend environment variables with Astro.js


Recently, I've been really digging the idea of transitional apps and "islands" architecture for multipage apps. To that point, I've been playing with Slinkity for 11ty and its contemporary AstroJS.

Astro is a great framework that lets you create pages and components in your favorite framework. I've really enjoyed playing with it so far.

Update: Nov. 20, 2024: While this post is still accurate and helpful, Astro has release the 5.0 beta which gives a new, type-safe way of handling environment variables that also solves this.

The problem: no process.env and no secure leakage

One under-documented issue that I just ran into was using environment variables in my client-side "islands." If you're using environment variables for convenience (not security), you may want them in your frontend components. It's not obvious how to accomplish this. When you use process.env.<ENV_VAR> you'll get a browser console error that process doesn't exist... too right, I guess!

The team helped me out via their Discord community and are going to be documenting this going forward.

The solution: import.meta.env and VITE_

The solution has two parts. First, we need something in the place of process.env, then we need to prefix our environment variables, so Vite can protect us from ourselves to avoid security leaks.

For any environment variable (in the environment, in a .env or .env.local, etc.), you can access them via import.meta.env.VITE_<ENV_KEY>. Note the prefix. All client-side variables need to be prefixed with VITE_.

So in setting up Algolia InstantSearch for my most recent streaming adventures, I needed the following code instead:

VITE_ALGOLIA_APP_ID = "myidhere"
VITE_ALGOLIA_SEARCH_KEY = "asearchonlykeyhere"
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch(import.meta.env.VITE_ALGOLIA_APP_ID, import.meta.env.VITE_ALGOLIA_SEARCH_KEY);

This solution is straight from the Discord and is pulled from the way Vite handles env variables.

Learning new technology like this is a lot of fun, but when it's super early in development, finding answers for problems like this can get hairy fast. Shoutout to the Astro team for being quick to help!