Static Sites with Astro
By the end of this lesson the Rohtak Tech Meetup site will have a shared layout, a header and an event card component, an events list built from a JSON file, one page per event, and a small script that runs in the browser. You will also read the real build output and know exactly what reaches visitors.
What you should know first: Set Up Your Jamstack Toolkit (we continue from that project and its folder layout), HTML basics, and JavaScript modules. Version used: Astro 7.4.12 on Node.js 26. All outputs below are from real builds.
The anatomy of an .astro file
An Astro component is a file ending in .astro. It has two parts:
- The component script (often called frontmatter) between two
---lines. It is JavaScript that runs at build time, on your computer or the build server. - The template below it: HTML with
{ }expressions, a bit like JSX.
Think of a tiffin service in Rohtak. The kitchen (the script) chops, cooks and packs. Only the packed tiffin (the template output) travels to the customer. The knives and the gas stove never leave the kitchen. In the same way, code in the component script never reaches the browser; only the HTML it produces does.
Two rules follow. Values in { } are escaped automatically: < becomes <, so text cannot turn into tags. And a <script> tag in the template is the only way to run code in the browser. We will use both rules below.
Step 1: a layout with a slot
Every page needs the same <head>, header and footer. A layout is a component that holds that shell. Create src/layouts/BaseLayout.astro:
---
import SiteHeader from "../components/SiteHeader.astro";
import "../styles/global.css";
const { title, description } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content={description} />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>{title} | Rohtak Tech Meetup</title>
</head>
<body>
<SiteHeader />
<main>
<slot />
</main>
<footer>
<p>Rohtak Tech Meetup: free, monthly, run by volunteers.</p>
</footer>
</body>
</html>Astro.props holds the attributes a page passes in, such as title. <slot /> marks where the page's own content goes. Importing global.css here applies it to every page that uses the layout. src/styles/global.css sets the font, margin: 0 on the body, and a centred main with max-width: 48rem.
Step 2: a header with scoped styles
Create src/components/SiteHeader.astro:
---
const path = Astro.url.pathname;
---
<header class="site-header">
<a class="logo" href="/">Rohtak Tech Meetup</a>
<nav aria-label="Main">
<a href="/" aria-current={path === "/" ? "page" : undefined}>Home</a>
<a href="/events/" aria-current={path.startsWith("/events") ? "page" : undefined}>Events</a>
</nav>
</header>
<style>
.site-header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
padding: 1rem;
background: #1e1b4b;
}
a {
color: white;
}
[aria-current="page"] {
font-weight: bold;
}
</style>Astro.url.pathname is the URL of the page being built. aria-current="page" tells screen readers which link is the current page; when the value is undefined, Astro leaves the attribute out. The <style> block is scoped: a { color: white; } affects only links in this component, not every link on the site. You will see how in the build output.
Step 3: data and an event card
Until the Headless CMS lesson, events live in src/data/events.json. Each event has the same keys. Here is one of the three:
{
"slug": "git-for-beginners-jan-2027",
"title": "Git for Absolute Beginners",
"date": "2027-01-09",
"startTime": "11:00",
"venue": "Model Town Community Hall, Rohtak",
"speaker": "Kabir Hooda",
"summary": "Commits, branches and your first pull request, with no fear.",
"tags": ["git"],
"seats": 40
}Dates need Indian formatting. Put the helper in src/lib/format.js so every component can share it:
// Shared helpers. Runs at build time, so the visitor's browser never downloads it.
const dateFormat = new Intl.DateTimeFormat("en-IN", {
dateStyle: "medium",
timeZone: "Asia/Kolkata",
});
export function formatDate(isoDate) {
return dateFormat.format(new Date(`${isoDate}T00:00:00+05:30`));
}The fixed time zone matters. Build servers usually run in UTC, and a date without a time zone can shift by a day there. Now the card, src/components/EventCard.astro:
---
import { formatDate } from "../lib/format.js";
const { event } = Astro.props;
---
<article class="event-card">
<h3><a href={`/events/${event.slug}/`}>{event.title}</a></h3>
<p>{formatDate(event.date)}, {event.startTime} | {event.speaker}</p>
<p>{event.summary}</p>
</article>
<style>
.event-card {
border: 1px solid #c7d2fe;
border-radius: 8px;
padding: 1rem;
}
</style>Step 4: the events list page
Files in src/pages/ become URLs. src/pages/events/index.astro becomes /events/:
---
import BaseLayout from "../../layouts/BaseLayout.astro";
import EventCard from "../../components/EventCard.astro";
import events from "../../data/events.json";
---
<BaseLayout title="Events" description="All upcoming Rohtak Tech Meetup sessions.">
<h1>Upcoming events</h1>
<ul class="event-list">
{events.map((event) => (
<li><EventCard event={event} /></li>
))}
</ul>
</BaseLayout>Importing a JSON file gives you a normal JavaScript array. events.map() returns one <li> per event, just like in React, but it runs once at build time. (The page also has a small scoped style that removes the bullets and uses a grid gap.)
Step 5: one page per event with getStaticPaths
The square brackets in src/pages/events/[slug].astro make a dynamic route: one file, many URLs. In a static build, Astro must know every URL in advance, so the page exports a function called getStaticPaths():
---
import BaseLayout from "../../layouts/BaseLayout.astro";
import events from "../../data/events.json";
import { formatDate } from "../../lib/format.js";
export function getStaticPaths() {
return events.map((event) => ({
params: { slug: event.slug },
props: { event },
}));
}
const { event } = Astro.props;
---
<BaseLayout title={event.title} description={event.summary}>
<h1>{event.title}</h1>
<dl>
<dt>When</dt>
<dd>{formatDate(event.date)}, {event.startTime}</dd>
<dt>Where</dt>
<dd>{event.venue}</dd>
<dt>Speaker</dt>
<dd>{event.speaker}</dd>
<dt>Seats</dt>
<dd>{event.seats}</dd>
</dl>
<p>{event.summary}</p>
<p><a href="/events/">All events</a></p>
</BaseLayout>Each returned object has params (fills [slug] in the URL) and props (handed to the page as Astro.props). The function is plain JavaScript, so you can run the same logic in the editor and see the list of URLs it creates:
// The same data and getStaticPaths() as src/pages/events/[slug].astro
const events = [
{ slug: "astro-basics-dec-2026", title: "Fast Websites with Astro" },
{ slug: "git-for-beginners-jan-2027", title: "Git for Absolute Beginners" },
{ slug: "accessible-forms-feb-2027", title: "Accessible Forms in Plain HTML" },
];
function getStaticPaths() {
return events.map((event) => ({
params: { slug: event.slug },
props: { event },
}));
}
// What Astro does with the result during the build
for (const { params, props } of getStaticPaths()) {
console.log(`/events/${params.slug}/ -> "${props.event.title}"`);
}
// A slug with a space or capital letters makes an ugly URL: check them
const bad = events.filter((e) => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e.slug));
console.log(bad.length === 0 ? "All slugs are URL-safe" : bad);/events/astro-basics-dec-2026/ -> "Fast Websites with Astro" /events/git-for-beginners-jan-2027/ -> "Git for Absolute Beginners" /events/accessible-forms-feb-2027/ -> "Accessible Forms in Plain HTML" All slugs are URL-safe
A slug that is not in the list gets a 404. The dev server explains why in its log:
19:04:27 [WARN] [router] A `getStaticPaths()` route pattern was matched, but no matching static path was found for requested path `/events/nope/`. Possible dynamic routes being matched: src/pages/events/[slug].astro. 19:04:27 [404] /events/nope/ 11ms
Step 6: a small script for the browser
The home page shows the next meetup and "Only N days to go!". The number of days changes every day, so it must not be frozen into the HTML at build time. That one line belongs in the browser. Here is src/pages/index.astro:
---
import BaseLayout from "../layouts/BaseLayout.astro";
import EventCard from "../components/EventCard.astro";
import events from "../data/events.json";
const nextEvent = events[0];
---
<BaseLayout title="Home" description="A free monthly meetup for developers and students in Rohtak.">
<h1>Rohtak Tech Meetup</h1>
<p>Learn, share and build with developers and students in Rohtak.</p>
<h2>Next meetup</h2>
<EventCard event={nextEvent} />
<p id="countdown" data-date={nextEvent.date}></p>
<script>
const el = document.getElementById("countdown");
const start = new Date(`${el.dataset.date}T00:00:00+05:30`);
const days = Math.ceil((start - Date.now()) / 86_400_000);
el.textContent = days > 0 ? `Only ${days} days to go!` : "See you there!";
</script>
</BaseLayout>The build-time code passes the date to the browser through a data-date attribute. Astro processes the <script>: it bundles and minifies it and turns it into type="module". A small script like this one is inlined into the HTML. Add is:inline to a script if you want it left exactly as written.
Keep the <script> inside the layout, as above. In our first try it sat after </BaseLayout>, and the built file ended with </html><script type="module">...</script>: a script outside the document. Browsers forgive it, but it is invalid HTML.
Step 7: build and read the output
npm run buildgenerating static routes 19:36:06 ├─ /events/astro-basics-dec-2026/index.html (+86ms) 19:36:06 ├─ /events/git-for-beginners-jan-2027/index.html (+21ms) 19:36:06 ├─ /events/accessible-forms-feb-2027/index.html (+13ms) 19:36:06 ├─ /events/index.html (+450ms) 19:36:07 ├─ /index.html (+272ms) 19:36:07 ✓ Completed in 1.14s. 19:36:08 [build] ✓ Completed in 7.74s. 19:36:08 [build] 5 page(s) built in 8.37s 19:36:08 [build] Complete!
dist/
├── events/
│ ├── accessible-forms-feb-2027/index.html
│ ├── astro-basics-dec-2026/index.html
│ ├── git-for-beginners-jan-2027/index.html
│ └── index.html
├── favicon.ico
├── favicon.svg
└── index.htmlFive HTML files, about 9 KB together. There is no JavaScript file and no CSS file. Our CSS was small, so Astro put it in a <style> tag in each page. Bigger stylesheets would be written as separate files. Here is the start of the built header:
<style>.site-header[data-astro-cid-fzpbxy5g]{background:#1e1b4b;flex-wrap:wrap;justify-content:space-between;gap:1rem;padding:1rem;display:flex}a[data-astro-cid-fzpbxy5g]{color:#fff}...</style>
<header class="site-header" data-astro-cid-fzpbxy5g><a class="logo" href="/" data-astro-cid-fzpbxy5g>Rohtak Tech Meetup</a>That explains scoped styles: Astro adds a unique attribute such as data-astro-cid-fzpbxy5g to the component's elements and to its CSS selectors. Notice also what is missing: formatDate, getStaticPaths and the JSON import left no trace. Only their results are in the HTML.
The page below is the built home page, tidied with line breaks so you can read it. Run it to see exactly what a visitor receives.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home | Rohtak Tech Meetup</title>
<style>
.site-header[data-astro-cid-fzpbxy5g]{background:#1e1b4b;flex-wrap:wrap;justify-content:space-between;gap:1rem;padding:1rem;display:flex}
a[data-astro-cid-fzpbxy5g]{color:#fff}
[data-astro-cid-fzpbxy5g][aria-current=page]{font-weight:700}
:root{color:#1f2937;font-family:system-ui,sans-serif;line-height:1.5}
body{margin:0}
main{max-width:48rem;margin-inline:auto;padding:1rem}
.event-card[data-astro-cid-j3v25qam]{border:1px solid #c7d2fe;border-radius:8px;padding:1rem}
</style>
</head>
<body>
<header class="site-header" data-astro-cid-fzpbxy5g><a class="logo" href="/" data-astro-cid-fzpbxy5g>Rohtak Tech Meetup</a><nav aria-label="Main" data-astro-cid-fzpbxy5g><a href="/" aria-current="page" data-astro-cid-fzpbxy5g>Home</a> <a href="/events/" data-astro-cid-fzpbxy5g>Events</a></nav></header>
<main>
<h1>Rohtak Tech Meetup</h1>
<p>Learn, share and build with developers and students in Rohtak.</p>
<h2>Next meetup</h2>
<article class="event-card" data-astro-cid-j3v25qam><h3 data-astro-cid-j3v25qam><a href="/events/astro-basics-dec-2026/" data-astro-cid-j3v25qam>Fast Websites with Astro</a></h3><p data-astro-cid-j3v25qam>12 Dec 2026, 10:30 | Priya Malik</p><p data-astro-cid-j3v25qam>Build a static site from scratch and see why it loads so quickly.</p></article>
<p id="countdown" data-date="2026-12-12"></p>
<script type="module">var e=document.getElementById(`countdown`),t=new Date(`${e.dataset.date}T00:00:00+05:30`),n=Math.ceil((t-Date.now())/864e5);e.textContent=n>0?`Only ${n} days to go!`:`See you there!`;</script>
</main>
<footer><p>Rohtak Tech Meetup: free, monthly, run by volunteers.</p></footer>
</body>
</html>The countdown line is the only thing computed in the browser. Everything else was decided at build time. (We added one space between the two nav links for readability.)
Escaping and set:html
Because { } escapes values, data from a CMS or a form cannot inject tags. We built a test page with a hostile "note":
---
const note = '<img src=x onerror="alert(1)"> Bring a laptop & charger';
---
<p id="a">{note}</p>
<p id="b" set:html={note} /><p id="a"><img src=x onerror="alert(1)"> Bring a laptop & charger</p><p id="b"><img src=x onerror="alert(1)"> Bring a laptop & charger</p>
The first paragraph is safe text. The second, with set:html, put a real <img> with an onerror handler into the page, which would run script for every visitor. Use set:html only for HTML you wrote yourself or have cleaned with a sanitiser. XSS Prevention explains the attack.
Adding a framework island
Astro components never ship JavaScript. If a part needs rich interactivity, such as a searchable speaker gallery, you can add React, Vue or Svelte with npx astro add react and mark the component with a directive, for example <SpeakerGallery client:visible />. Without a client: directive, the component is rendered to HTML only. The trade-offs are covered in Static, SSR & Hybrid Sites; for most of this site, plain Astro and small scripts are enough.
Common mistakes
- Expecting frontmatter code to run in the browser. It runs once at build time. Use a
<script>for anything that must happen on the visitor's device. - Forgetting
getStaticPaths()in a[slug].astropage. A static build cannot guess the URLs and stops with an error. - Using
set:htmlon outside data. It disables escaping. - Dates without a time zone. A build server in UTC can show the wrong day; fix the zone as in
format.js. - Global styles in a component. A
<style>in a component is scoped; put site-wide rules inglobal.css.
Interview questions
1. Where does the code in an Astro component's frontmatter run?
At build time for static pages (or on the server for on-demand pages), never in the browser. Only the HTML it produces is sent, so imports and helpers used there add no JavaScript to the page.
2. What does getStaticPaths() return, and why is it needed?
An array of objects, each with params that fill the dynamic part of the route and optional props for the page. In a static build every URL must be known before deployment, so Astro calls it to know which pages to generate.
3. How does Astro scope component CSS?
It adds a unique data-astro-cid-* attribute to the component's elements and rewrites the component's selectors to include it. Styles in one component therefore cannot leak into another.
4. What is the difference between a normal <script> and <script is:inline> in Astro?
A normal script is processed: bundled, minified, deduplicated, turned into type="module", and inlined only if small. is:inline leaves the script exactly as written, with no imports resolved.
Key points
- An
.astrofile has a build-time script between---lines and an HTML template. - Layouts use
<slot />; components receive data throughAstro.props. - Component
<style>blocks are scoped withdata-astro-cid-*attributes. [slug].astroplusgetStaticPaths()turns one template and a data file into many pages.- Only
<script>tags (andclient:islands) run in the browser; keep them inside the layout. { }escapes values;set:htmldoes not, so never use it on untrusted data.
Exercise
Add a speakers page to the meetup site. Create src/pages/speakers.astro that uses BaseLayout, reads events.json, and lists each speaker's name with the title of their talk as a link to the event page. Add a "Speakers" link to SiteHeader.astro with the correct aria-current. Build the site and check that dist/speakers/index.html exists and the build log now says 6 pages.
Show solution
---
import BaseLayout from "../layouts/BaseLayout.astro";
import events from "../data/events.json";
---
<BaseLayout title="Speakers" description="People speaking at the Rohtak Tech Meetup.">
<h1>Speakers</h1>
<ul>
{events.map((event) => (
<li>
{event.speaker}: <a href={`/events/${event.slug}/`}>{event.title}</a>
</li>
))}
</ul>
</BaseLayout>In the header nav, add <a href="/speakers/" aria-current={path.startsWith("/speakers") ? "page" : undefined}>Speakers</a>. Astro builds trailing-slash URLs as folders, so the new page is written to dist/speakers/index.html and the build log shows 6 pages. The speaker names stay escaped because they are inside { }.
Quick Quiz
1. Where does formatDate() run when it is called in a component's frontmatter during a static build?
Frontmatter runs at build time; only the resulting text reaches the HTML.
2. What does src/pages/events/[slug].astro need in a static build?
Astro must know every slug in advance to write one HTML file per event.
3. Why did the built header CSS contain [data-astro-cid-fzpbxy5g]?
The attribute keeps a component's styles from affecting other components.
4. Which template line can inject a working <img onerror> from CMS data?
set:html inserts raw HTML; { } escapes it.
Learn Jamstack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
