How to Use import.meta.env in Astro for Environment Variables
In Astro, you access environment variables using
import.meta.env. Variables prefixed with PUBLIC_ are exposed to client-side code, while others remain server-only. Use import.meta.env.PUBLIC_YOUR_VAR to safely use environment variables in your components.Syntax
The import.meta.env object holds all environment variables available to your Astro project. Variables starting with PUBLIC_ are exposed to the browser, while others are only available on the server.
Access variables like this:
import.meta.env.PUBLIC_VARIABLE_NAMEfor client and serverimport.meta.env.SECRET_VARIABLE_NAMEonly on server
js
const apiUrl = import.meta.env.PUBLIC_API_URL; const secretKey = import.meta.env.SECRET_KEY; console.log('Public API URL:', apiUrl); console.log('Secret Key:', secretKey);
Output
Public API URL: https://api.example.com
Secret Key: undefined (if run on client)
Example
This example shows how to use import.meta.env in an Astro component to display a public environment variable.
astro
--- const siteName = import.meta.env.PUBLIC_SITE_NAME || 'Default Site'; --- <html lang="en"> <head> <title>{siteName}</title> </head> <body> <h1>Welcome to {siteName}!</h1> </body> </html>
Output
<h1>Welcome to My Astro Site!</h1>
Common Pitfalls
1. Forgetting the PUBLIC_ prefix: Only variables prefixed with PUBLIC_ are exposed to client-side code. Without this prefix, variables will be undefined in the browser.
2. Not restarting the dev server: Changes to environment variables require restarting Astro's dev server to take effect.
3. Exposing secrets accidentally: Never prefix sensitive keys with PUBLIC_ as they become visible in client code.
js
/* Wrong: Trying to access secret key on client */ const secret = import.meta.env.SECRET_KEY; // undefined in browser /* Right: Use only public variables in client code */ const publicApi = import.meta.env.PUBLIC_API_URL;
Quick Reference
| Feature | Usage | Notes |
|---|---|---|
| Access env variable | import.meta.env.VAR_NAME | Use PUBLIC_ prefix for client exposure |
| Client-side variable | import.meta.env.PUBLIC_VAR | Available in browser and server |
| Server-only variable | import.meta.env.SECRET_VAR | Not exposed to browser |
| Restart server | After changing .env files | Required to update env variables |
| Avoid exposing secrets | Do not prefix secrets with PUBLIC_ | Keep sensitive data safe |
Key Takeaways
Use import.meta.env to access environment variables in Astro.
Prefix variables with PUBLIC_ to expose them to client-side code.
Never expose sensitive keys by prefixing them with PUBLIC_.
Restart the Astro dev server after changing environment variables.
Use import.meta.env only in supported Astro files and components.