Understand Astro Front Matter for Component Scripts
Astro components let you add special code at the very top of your component files. This code sits between two sets of three dashes (—). Astro calls this area “front matter.” It’s a powerful place to add information, or metadata, to your component. You might have seen front matter in Markdown files before, but Astro uses it to include JavaScript or TypeScript code directly within your components.
This front matter section is where you can write code that runs *before* your component is shown. Think of it as a setup area for your component. You can use it to bring in other files or components you need, like the layout file we’ve already used. You can also set up special containers for information, called variables, that your component will use later. It’s even a place to grab information from a database or prepare data that the component will receive from elsewhere, which we call props.
Why Front Matter Code Stays Safe
The most important thing about the code in your front matter is that it *never* runs in the user’s web browser. Astro builds your web pages either when you first create them (at build time) or when someone asks for a page (on demand on the server). Code in the front matter is never sent to the browser. This means you can safely write sensitive information or commands here. For example, you could connect to a database or run other code that you don’t want users to see.
Step 1: Add a Simple Variable
Let’s start with a basic example. Inside the front matter (between the dashes), create a new constant. We’ll call it user. Set its value to a simple text string, like Mario. This variable now holds the name “Mario” for your component to use.
---
const user = "Mario";
---
Step 2: Display the Variable in Your Component
Now, you can use this user variable in the main part of your component, which is called the template. Find the welcome message in your component. After the welcome message, add a comma and then type curly braces: {}. Inside these curly braces, put the name of your variable: user. When Astro builds your page, it will replace {user} with the actual word “Mario”. Your welcome message will now show “Welcome Mario!”
---
const user = "Mario";
---
Welcome {user}!
Step 3: Use an Object for More Data
Instead of just a name, you can store more information in your variable by making it an object. An object is like a container that holds different pieces of information, each with its own label. Let’s change our user variable. Instead of just "Mario", let’s make it an object with two labels: name and email. The name will be "Mario", and the email can be "[email protected]".
---
const user = {
name: "Mario",
email: "[email protected]"
};
---
Step 4: Access Object Properties in the Template
Now that user is an object, you can show its different parts. Update your welcome message to show the name using user.name inside the curly braces. Then, add a new paragraph below it. This paragraph can say “Logged in as ” followed by {user.email} inside curly braces. Astro will now display both the name and the email address.
---
const user = {
name: "Mario",
email: "[email protected]"
};
---
Welcome {user.name}!
Logged in as {user.email}
Step 5: Simulate Dynamic Data with a Function
In a real website, you wouldn’t usually write a user’s name and email directly into the code. You’d often fetch this information when someone visits the page. To show how this works, let’s make the user variable sometimes have information and sometimes be empty (null). This simulates a user being logged in or out.
First, create a function called getUser above where you define the user constant. This function will randomly decide whether to return the user object or null. Then, change the line where you define user to call this new getUser() function. Now, each time the page is requested during development, it will randomly show user details or nothing.
---
function getUser() {
// Generates a random number between 0 and 1
if (Math.random() < 0.5) {
return null; // User is not logged in
} else {
return {
name: "Mario",
email: "[email protected]"
};
}
}
const user = getUser();
---
Step 6: Add Conditional Display Logic
Because the user variable might be null, Astro shows errors. It knows you can’t get a name or email from something that doesn’t exist. To fix this, you need to tell Astro to only show the user’s details *if* there is a user. You can do this in a couple of ways.
One way is to add a question mark after the variable name: user?.name. This tells JavaScript to only try and get the name if user actually has a value. Another, often cleaner, way is to use a special pattern: {user && (...)}. This checks if user is true (meaning it has a value). If it is true, then it shows whatever is inside the parentheses. This is very similar to how you might show content conditionally in other tools like React.
---
function getUser() {
if (Math.random() < 0.5) {
return null;
} else {
return {
name: "Mario",
email: "[email protected]"
};
}
}
const user = getUser();
---
{user && (
Welcome {user.name}!
Logged in as {user.email}
)}
Step 7: Test Conditional Rendering
Now, when you look at your page in the browser during development, you’ll see the welcome message and email sometimes, and sometimes you won’t see anything related to the user. Refresh the page several times. You should see the content appear and disappear randomly. This proves that your conditional logic is working correctly. It only shows the user details when the user variable actually has data.
Remember, this random behavior happens during development. When you build your website for real, the code runs once. If you want to show different content based on whether a user is logged in when the site is live, you would typically use server-side rendering. This allows the server to check the user’s login status right when they ask for the page and then send back the correct version.
Source: Astro Crash Course #5 – Templating (YouTube)