Core Fundamentals: Pages & Routing
6 min read
Core Fundamentals: Pages & Routing 🚀
Welcome to the second module of your Astro journey. In this section, we transition from the theoretical architecture of Astro to the tangible mechanics of building a website structure.
We will explore how Astro interprets your file system to generate URLs, how to template thousands of pages programmatically without insanity, and how to maintain a visual consistency across your universe of pages.
1. File-based Routing: Structuring Your URLs 📂
Definition & Problem
The Problem: In many traditional Single Page Application (SPA) frameworks or older server-side languages, creating a new route (a URL like /about or /contact) often requires two steps: creating the view file and updating a central configuration file (router.js, routes.py, etc.) to tell the server that "URL X maps to File Y." As applications grow, these router files become massive, complex, and prone to merge conflicts.
The Solution: File-based routing. The file system is the API. The structure of your project directory dictates the structure of your website's URLs.
The Concept
Astro looks for .astro, .md, .mdx, .html, or .js/.ts files inside the src/pages/ directory. Each file automatically becomes a route based on its filename.
How It Works
There are three primary behaviors you must understand:
- Index Routes: A file named
index.astroinside a folder resolves to the folder's root. - Static Routes: A named file resolves to that name.
- Nested Routes: Subfolders create URL segments.
Examples
| File Location | Generated URL |
|---|---|
src/pages/index.astro |
/ (The home page) |
src/pages/about.astro |
/about |
src/pages/contact.md |
/contact |
src/pages/blog/index.astro |
/blog |
src/pages/blog/news.astro |
/blog/news |
Interesting Fact: The concept of file-based routing isn't new to the modern web. It dates back to the early days of PHP in the 1990s, where
example.com/info.phpliterally served theinfo.phpfile from the disk. We have come full circle, but now with better security and build steps!
Industry Standard Practice
Avoid using spaces or capital letters in your filenames inside src/pages. While some operating systems are case-insensitive, web servers (like Linux-based Nginx or Apache) are strictly case-sensitive. MyFile.astro might work locally but fail in production. Always use kebab-case (e.g., my-file.astro).
2. Dynamic Routing: Handling Multiple Pages Elegantly 🧬
Definition & Problem
The Problem: Imagine you are building a product catalog with 5,000 items. Creating 5,000 individual files (item-1.astro, item-2.astro...) is physically impossible to maintain. If you wanted to change the layout, you would have to edit 5,000 files.
The Solution: Dynamic Routing. You create a single file that acts as a blueprint. This file accepts a parameter (like an ID or a "slug") and generates pages for every data item you possess.
The Concept
In Astro, dynamic parameters are defined by wrapping the filename in square brackets: [param].astro.
Because Astro is primarily a Static Site Generator (SSG), it needs to know exactly which paths to build at build time. We provide this list using a required export function called getStaticPaths.
Implementation
Let's say we want to create a page for three different dogs: Clifford, Rover, and Spot. We create one file: src/pages/dogs/[dog].astro.
src/pages/dogs/[dog].astro
---
// 1. getStaticPaths is required for static dynamic routes
export function getStaticPaths() {
return [
// Each object must have a 'params' property
{ params: { dog: 'clifford' } },
{ params: { dog: 'rover' } },
{ params: { dog: 'spot' } },
];
}
// 2. Access the parameter for the current page
const { dog } = Astro.params;
---
<h1>Hello, {dog}!</h1>
<p>This is a page generated specifically for {dog}.</p>Passing Props
You can also pass data associated with the route directly via props, so you don't have to fetch it again.
---
export function getStaticPaths() {
return [
{
params: { id: '1' },
props: { title: 'First Post', content: '...' }
},
];
}
const { id } = Astro.params;
const { title, content } = Astro.props;
---
<h1>{title}</h1>Rest Parameters (Catch-all)
If you need to match routes of any depth (e.g., /docs/v1/setup/install), you can use the JavaScript spread syntax inside the brackets: [...path].astro.
Imagination Break: Imagine writing a dictionary website manually. You finish "Aardvark" through "Azimuth," look at the calendar, realize 40 years have passed, and you haven't even started the letter "B." Dynamic routing is the printing press that saves you from this fate.
3. Page Layouts: Creating Consistent Designs 📐
Definition & Problem
The Problem: Every HTML page requires a <!DOCTYPE html>, <html>, <head>, and <body> tag. Copying and pasting this boilerplate into every single .astro page inside src/pages/ violates the "DRY" (Don't Repeat Yourself) principle. If you want to add a Google Analytics script to the <head>, you would have to edit every file manually.
The Solution: Layout Components. These are specialized Astro components designed to wrap your page content, providing a shared shell.
The Concept
Astro uses the <slot /> element to inject content. A Layout is simply a component that contains the <html> shell and a <slot /> where the specific page content will be rendered.
Implementation
Step 1: Create the Layout (src/layouts/MyLayout.astro)
---
// Access props passed from the page
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{title}</title>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<nav>My Shared Navigation</nav>
<!-- The specific page content will appear here -->
<slot />
<footer>© 2026 Astro Guide</footer>
</body>
</html>Step 2: Use the Layout (src/pages/index.astro)
---
import MyLayout from '../layouts/MyLayout.astro';
---
<MyLayout title="Home Page">
<h1>Welcome to the Future</h1>
<p>This content is injected into the slot.</p>
</MyLayout>Named Slots
For complex layouts, you might need content in multiple places (e.g., a custom sidebar and the main content).
In Layout:
<header><slot name="header-content" /></header>
<main><slot /></main> <!-- Default slot -->In Page:
<h1 slot="header-content">I go in the header!</h1>
<p>I go in the default slot.</p>4. The 404 Page: Handling Missing Routes 🚫
Definition & Problem
The Problem: Users make mistakes. They type URLs incorrectly, or follow broken links. By default, web servers show a generic, austere error message or the browser's default "Page Not Found" screen, which looks unprofessional and causes users to leave the site immediately.
The Solution: A custom 404 page. This retains your branding and provides navigation options to guide the user back to safety.
The Concept
Astro looks for a specific file named 404.astro (or 404.md, 404.html) in the src/pages/ directory.
Implementation
Create src/pages/404.astro.
---
import MyLayout from '../layouts/MyLayout.astro';
---
<MyLayout title="Page Not Found">
<div class="error-container">
<h1>404</h1>
<p>Houston, we have a problem.</p>
<p>The coordinates you entered lead to empty space.</p>
<a href="/">Return to Earth (Home)</a>
</div>
</MyLayout>Important Usage Notes
- Production vs. Development: In development (
npm run dev), Astro might show you a helpful error overlay if you try to access a broken route. To see your actual 404 page, you often need to preview the build locally (npm run build && npm run preview) or click the link provided in the dev overlay. - Deployments: Most modern hosts (Vercel, Netlify, Cloudflare Pages) automatically detect the
404.htmlgenerated by this file and serve it when a user hits a non-existent route.
Summary
You have now mastered the cartography of Astro. You can create static landmarks (File-based Routing), generate infinite worlds from data (Dynamic Routing), ensure structural integrity (Layouts), and handle lost travelers (404 Pages).
References & Further Reading
Challenge
You are tasked with setting up the foundational page and routing structure for a new e-commerce website using Astro. You need to create four separate components within the provided editor, following the file paths indicated by the comments.
src/layouts/BaseLayout.astro: Create a reusable layout component. It must accept a single prop,titleof typestring. This title should be used within the<title>tag of the HTML document. The component's body must contain a<slot />to render page-specific content.src/pages/company/about-us.astro: Create a static page that represents the path/company/about-us. This page must use theBaseLayoutyou created. Pass the string "About Our Company" as thetitleprop to the layout. Inside the page, add an<h1>tag with the text "About Us".src/pages/products/[productId].astro: Create a dynamic route to handle individual product pages.- This component must export an async function
getStaticPathsthat pre-renders pages for three specific products. Theparamsfor these pages should have aproductIdof:'super-widget','mega-gadget', and'ultra-thingy'. - The page must use the
BaseLayout. The HTML page title should be dynamically set to "Product: [productId]", where[productId]is the ID from the URL. - The page content should display the product ID within an
<h2>tag.
- This component must export an async function
src/pages/404.astro: Create a custom 404 "Not Found" page. It should use theBaseLayoutwith thetitleprop set to "Page Not Found". The body should contain an<h1>with the text "404 - Not Found" and a paragraph<p>with the text "Sorry, the page you are looking for does not exist.".
Expected result
Your solution should consist of four distinct Astro components, structured as follows.
1. src/layouts/BaseLayout.astro
A layout component with a basic HTML5 boilerplate. It correctly defines and uses a title prop for the <title> tag and includes a <slot /> in the <body> for content injection.
---
export interface Props {
title: string;
}
const { title } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
</head>
<body>
<main>
<slot />
</main>
</body>
</html>2. src/pages/company/about-us.astro
A static page that imports and uses the BaseLayout. It passes the required "About Our Company" string to the title prop and includes the specified <h1>.
---
import BaseLayout from '../../layouts/BaseLayout.astro';
---
<BaseLayout title="About Our Company">
<h1>About Us</h1>
</BaseLayout>3. src/pages/products/[productId].astro
A dynamic route page. It must contain a correctly implemented getStaticPaths function returning an array with three objects, each containing a params object with a productId. The component part uses Astro.params to render the dynamic data and passes a dynamic title to the BaseLayout.
---
import BaseLayout from '../../layouts/BaseLayout.astro';
export async function getStaticPaths() {
return [
{ params: { productId: 'super-widget' } },
{ params: { productId: 'mega-gadget' } },
{ params: { productId: 'ultra-thingy' } },
];
}
const { productId } = Astro.params;
---
<BaseLayout title={`Product: ${productId}`}>
<h2>Product Details for: {productId}</h2>
</BaseLayout>4. src/pages/404.astro
A custom 404 page that utilizes BaseLayout. It provides a static title and contains the specified <h1> and <p> tags for the error message.
---
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Page Not Found">
<h1>404 - Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</BaseLayout>