Consider an Astro component that uses an environment variable API_KEY. Which option correctly accesses this variable in the component?
const apiKey = import.meta.env.API_KEY; export default function Component() { return <p>{apiKey}</p>; }
Astro uses import.meta.env to access environment variables at build time.
Astro exposes environment variables through import.meta.env. Using process.env or Astro.env is not supported in component scripts.
Astro supports public and private environment variables. Which syntax correctly loads a private variable SECRET_KEY that should not be exposed to client code?
Private environment variables are only accessible on the server side in Astro.
In Astro, private environment variables (without PUBLIC_ prefix) are only accessible in server-side code such as server routes or Astro components rendered on the server. They are not available in client-side code.
Given this Astro component code:
--- const apiKey = process.env.API_KEY; ---{apiKey}
Why does it fail to display the API key?
const apiKey = process.env.API_KEY;
export default function Component() {
return <p>{apiKey}</p>;
}Astro uses a different syntax than Node.js for environment variables.
Astro does not support process.env in components. Instead, environment variables are accessed via import.meta.env. Using process.env will be undefined.
Consider this Astro server route code:
export async function get() {
return new Response(JSON.stringify({ key: import.meta.env.SECRET_KEY }), {
headers: { 'Content-Type': 'application/json' }
});
}If SECRET_KEY is set to supersecret in the environment, what is the JSON response?
export async function get() { return new Response(JSON.stringify({ key: import.meta.env.SECRET_KEY }), { headers: { 'Content-Type': 'application/json' } }); }
Server routes can access private environment variables directly.
Since SECRET_KEY is set and accessed in a server route, the response JSON contains the correct value.
Astro requires public environment variables to start with PUBLIC_. Why is this naming convention important?
Think about what data should be safe from client exposure.
The PUBLIC_ prefix signals Astro to expose those variables to client-side code. Variables without this prefix remain private and only accessible on the server, helping protect sensitive information.