Performance: Handling environment variables
This affects page load speed and bundle size by controlling which environment variables are exposed to client-side code.
const apiKey = import.meta.env.PUBLIC_API_KEY; // Only variables prefixed with PUBLIC_ are exposed to client console.log(apiKey);
const apiKey = import.meta.env.PUBLIC_API_KEY; // Using PUBLIC_ prefix for unnecessary or sensitive vars in client-side code console.log(apiKey);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Exposing unnecessary env vars client-side | N/A | 0 | Increased due to larger JS | [X] Bad |
| Exposing only PUBLIC_ prefixed vars | N/A | 0 | Minimal JS size impact | [OK] Good |
import.meta.env object to expose environment variables.process.env is common in Node.js but not in Astro client code. window.env and Astro.env are not valid in Astro.PUBLIC_ to expose them to client-side code.SERVER_ is not used for client exposure, CLIENT_ and ASTRO_ are not recognized prefixes in Astro.const apiKey = import.meta.env.PUBLIC_API_KEY; console.log(apiKey);
PUBLIC_API_KEY is set to 12345, what will be logged in the browser console?PUBLIC_, it is exposed to client code and accessible via import.meta.env.PUBLIC_API_KEY.PUBLIC_API_KEY is set to 12345, so console.log(apiKey) outputs the string "12345".const secret = import.meta.env.SECRET_KEY; console.log(secret);
SECRET_KEY is set in the environment but not prefixed with PUBLIC_.PUBLIC_ prefix are only available on the server side and not exposed to client code.import.meta.env.SECRET_KEY in client code results in undefined, so console.log(secret) logs "undefined".PUBLIC_ prefix are only available on the server side in Astro, so store the API key without the prefix and access it only in server-side code.Pass the test and this pattern moves unknown