0
0
AstroHow-ToBeginner ยท 3 min read

How to Use Environment Variables in Astro Projects

In Astro, you use environment variables by prefixing them with PUBLIC_ for client-side access and accessing them via import.meta.env. Variables without the prefix are only available on the server side during build or runtime.
๐Ÿ“

Syntax

Astro uses import.meta.env to access environment variables. Variables starting with PUBLIC_ are exposed to client-side code, while others remain server-only.

  • import.meta.env.PUBLIC_MY_VAR: Accesses a public env variable in client or server code.
  • import.meta.env.MY_SECRET: Accesses a server-only env variable.

Define variables in a .env file or your system environment.

javascript
/* .env file */
PUBLIC_API_URL=https://api.example.com
MY_SECRET_KEY=supersecret

// Access in Astro component or script
const apiUrl = import.meta.env.PUBLIC_API_URL;
const secret = import.meta.env.MY_SECRET_KEY; // only server-side
๐Ÿ’ป

Example

This example shows how to use a public environment variable in an Astro component to display an API URL on the page.

astro
---
const apiUrl = import.meta.env.PUBLIC_API_URL;
---
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Env Variable Example</title>
  </head>
  <body>
    <h1>API URL from Env Variable:</h1>
    <p>{apiUrl}</p>
  </body>
</html>
Output
<h1>API URL from Env Variable:</h1> <p>https://api.example.com</p>
โš ๏ธ

Common Pitfalls

  • Not prefixing variables with PUBLIC_ when you want to use them in client-side code causes them to be undefined.
  • Forgetting to restart the Astro dev server after changing .env files means changes won't apply.
  • Exposing sensitive data by using PUBLIC_ prefix on secrets is a security risk.
javascript
/* Wrong: Trying to use secret in client code */
const secret = import.meta.env.MY_SECRET_KEY; // undefined in client

/* Right: Use only public variables in client code */
const apiUrl = import.meta.env.PUBLIC_API_URL;
๐Ÿ“Š

Quick Reference

Variable TypePrefixAccessible InExample
PublicPUBLIC_Client & Serverimport.meta.env.PUBLIC_API_URL
PrivateNoneServer onlyimport.meta.env.MY_SECRET_KEY
โœ…

Key Takeaways

Prefix env variables with PUBLIC_ to use them in client-side Astro code.
Access env variables using import.meta.env in your Astro files.
Keep secrets without PUBLIC_ prefix to restrict them to server-side only.
Restart Astro dev server after changing .env files to apply updates.
Never expose sensitive data by adding PUBLIC_ prefix.