DEV Community

Bryan Robinson
Bryan Robinson

Posted on • Originally published at bryanlrobinson.com on

2

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.

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"
Enter fullscreen mode Exit fullscreen mode
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch(import.meta.env.VITE_ALGOLIA_APP_ID, import.meta.env.VITE_ALGOLIA_SEARCH_KEY);
Enter fullscreen mode Exit fullscreen mode

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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs