Components and layouts
The anatomy of an Astro component
Separate render-time logic from the template and understand where each part executes.
8 minute lesson
An .astro file combines render-time JavaScript with an HTML template:
---
const name = "Ada"
const greeting = name.toUpperCase()
---
<h2>Hello {greeting}</h2>
The fenced script runs when Astro renders the component: during the build for a static page, or on the server for an on-demand page. It can import files, read props, fetch data, and calculate values. Its code is not sent to the browser.
The template uses those values to produce HTML. View the page source and you will see <h2>Hello ADA</h2>, not the JavaScript that created it.
This distinction is the foundation of Astro:
- code between the fences prepares the document
- template expressions decide which HTML is emitted
- a
<script>tag runs later in the visitor’s browser
Add console.log("rendering") inside the fenced script and another log inside a <script> tag. The first appears in the build or server terminal. The second appears in browser DevTools. That small experiment makes the two runtimes concrete.
Lesson completed