0
0
Astroframework~20 mins

Handling environment variables in Astro - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling environment variables in Astro
📖 Scenario: You are building a simple Astro website that needs to use a secret API key safely. Instead of hardcoding the key in your code, you will use environment variables to keep it secure and flexible.
🎯 Goal: Learn how to set up and use environment variables in an Astro project to access a secret API key inside a component.
📋 What You'll Learn
Create an environment variable file with a secret API key
Configure Astro to load environment variables
Access the environment variable inside an Astro component
Display the API key value safely in the component
💡 Why This Matters
🌍 Real World
Environment variables are used in real projects to keep secrets like API keys safe and to configure apps without changing code.
💼 Career
Knowing how to handle environment variables is essential for web developers to build secure and flexible applications.
Progress0 / 4 steps
1
Create the environment variable file
Create a file named .env in the root of your Astro project. Inside it, add the line PUBLIC_API_KEY=12345abcde exactly as shown.
Astro
Hint

The .env file should be in the root folder of your Astro project. Use the exact variable name PUBLIC_API_KEY and value 12345abcde.

2
Configure Astro to load environment variables
In your astro.config.mjs file, import dotenv/config at the top to enable loading environment variables from the .env file.
Astro
Hint

Adding import 'dotenv/config' at the top of astro.config.mjs loads your environment variables automatically.

3
Access the environment variable inside an Astro component
Create an Astro component file named ApiKeyDisplay.astro. Inside the frontmatter, create a constant apiKey that reads Astro.env.PUBLIC_API_KEY.
Astro
Hint

Use the frontmatter section --- to declare const apiKey = Astro.env.PUBLIC_API_KEY. Then display it inside a paragraph.

4
Complete the component to display the API key
Ensure your ApiKeyDisplay.astro component returns a paragraph element that shows the text Your API key is: followed by the apiKey variable inside curly braces.
Astro
Hint

The paragraph should exactly read <p>Your API key is: {apiKey}</p> to display the key.