0
0
AstroHow-ToBeginner ยท 3 min read

How to Add Frontmatter in Astro: Simple Guide

In Astro, add frontmatter by placing JavaScript or TypeScript code inside a top-level --- block at the start of your file. This block lets you declare variables, import modules, and write logic that the component can use.
๐Ÿ“

Syntax

The frontmatter in Astro is a code block enclosed by triple dashes --- at the top of your file. Inside this block, you write JavaScript or TypeScript code. This code runs before the component renders and can define variables, import statements, or functions.

  • ---: Marks the start and end of the frontmatter block.
  • JavaScript/TypeScript code: Any valid code to prepare data or logic.
astro
---
const title = 'Welcome to Astro!';
const count = 5;
---
๐Ÿ’ป

Example

This example shows how to add frontmatter to define a title variable and use it inside the component's HTML. The frontmatter block sets the variable, and the template renders it.

astro
---
const title = 'Hello from Astro Frontmatter!';
---

<html lang="en">
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>{title}</h1>
    <p>This page uses frontmatter to set the title.</p>
  </body>
</html>
Output
<html lang="en"> <head> <title>Hello from Astro Frontmatter!</title> </head> <body> <h1>Hello from Astro Frontmatter!</h1> <p>This page uses frontmatter to set the title.</p> </body> </html>
โš ๏ธ

Common Pitfalls

Common mistakes when adding frontmatter in Astro include:

  • Forgetting the --- lines to open and close the frontmatter block.
  • Writing code outside the frontmatter block that should be inside it.
  • Using invalid JavaScript syntax inside the frontmatter.
  • Trying to use frontmatter variables without curly braces {} in the template.
astro
---
const message = 'Hi!'
// Missing closing dashes

<html>
  <body>
    <h1>{message}</h1>
  </body>
</html>

---

// Correct way:
---
const message = 'Hi!';
---
<html>
  <body>
    <h1>{message}</h1>
  </body>
</html>
๐Ÿ“Š

Quick Reference

Remember these tips when using frontmatter in Astro:

  • Always start and end the frontmatter with ---.
  • Write valid JavaScript or TypeScript inside the block.
  • Use curly braces {} to insert frontmatter variables in your template.
  • Frontmatter runs once before rendering, so use it for setup and data preparation.
โœ…

Key Takeaways

Add frontmatter in Astro by enclosing JavaScript code between triple dashes --- at the top of the file.
Use frontmatter to declare variables and import modules that your component can use.
Always close the frontmatter block properly to avoid syntax errors.
Insert frontmatter variables into your template using curly braces {}.
Frontmatter runs before rendering and helps prepare data for your component.