0
0
Astroframework~5 mins

Handling environment variables in Astro

Choose your learning style9 modes available
Introduction

Environment variables help keep secret or changing information outside your code. This makes your app safer and easier to update.

You want to keep API keys secret and not share them in your code.
You need to change settings like database URLs without changing code.
You want different settings for development and production.
You want to avoid hardcoding passwords or tokens in your project.
Syntax
Astro
import.meta.env.MY_VARIABLE

Use import.meta.env to access environment variables in Astro.

Variables must start with PUBLIC_ to be exposed to client-side code.

Examples
Access a public environment variable for client-side use.
Astro
const apiKey = import.meta.env.PUBLIC_API_KEY;
Access a server-only environment variable (not exposed to browser).
Astro
const secret = import.meta.env.MY_SECRET;
Check the current environment mode (development or production).
Astro
console.log(import.meta.env.MODE);
Sample Program

This Astro component reads a public environment variable PUBLIC_API_URL and shows it on the page.

Make sure to define PUBLIC_API_URL in your .env file before running.

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:</h1>
    <p>{apiUrl}</p>
  </body>
</html>
OutputSuccess
Important Notes

Environment variables without PUBLIC_ prefix are only available on the server side.

Restart your Astro dev server after changing environment variables.

Never commit secret keys to public repositories.

Summary

Use import.meta.env to access environment variables in Astro.

Prefix variables with PUBLIC_ to use them in client code.

Keep secrets safe by only using them on the server side.