0
0
AstroHow-ToBeginner ยท 3 min read

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_NAME for client and server
  • import.meta.env.SECRET_VARIABLE_NAME only 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

FeatureUsageNotes
Access env variableimport.meta.env.VAR_NAMEUse PUBLIC_ prefix for client exposure
Client-side variableimport.meta.env.PUBLIC_VARAvailable in browser and server
Server-only variableimport.meta.env.SECRET_VARNot exposed to browser
Restart serverAfter changing .env filesRequired to update env variables
Avoid exposing secretsDo 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.