Learn Astro Β· 1/15

Blast Off! Introduction to Astro

6 min read

1. The 'Why' Before the 'How': What is Astro?

Definition:
Astro is a modern web framework specifically designed for building content-driven websites such as blogs, marketing sites, and e-commerce catalogs. It creates Multi-Page Applications (MPAs) that render to HTML on the server by default, shipping zero JavaScript to the client unless explicitly requested.

The Problem: The JavaScript Tax
In the last decade, the web shifted heavily toward Single Page Applications (SPAs) using frameworks like React, Vue, or Angular. While powerful for complex dashboards (like Gmail or Trello), SPAs introduce a significant performance cost for simple content sites.

  1. Empty HTML: The server sends a nearly empty HTML shell.
  2. Hydration: The browser must download, parse, and execute a massive JavaScript bundle to "paint" the content.
  3. TTI (Time to Interactive): Users see a white screen or a spinner while the device struggles to process the code.

The Solution: Multi-Page Applications (MPAs)
Astro rejects the SPA model for content sites. Instead, it adopts the MPA model, similar to traditional server-side frameworks (like PHP or early Rails), but with modern developer tooling.

  • Server-First: Astro generates HTML on the server (or at build time). The browser receives fully populated content immediately.
  • Zero-JS by Default: If you build a static page in Astro, the final production build contains 0kb of framework JavaScript. It is pure HTML and CSS.
  • Framework Agnostic: You can still use React, Vue, Svelte, or Solid components inside Astro, but they are rendered to static HTML unless you specifically ask for interactivity.

πŸ’‘ Did You Know?

The concept of "Zero JavaScript By Default" essentially returns us to the foundational principles of the early webβ€”serving documents, not applicationsβ€”but allows us to author them using the modern component-based architecture we have grown to love.


2. Demystifying the Islands Architecture 🏝️

Definition:
Islands Architecture is a performance paradigm where a web page is treated as a static HTML document with isolated "slots" (Islands) of interactivity.

Technical Explanation: Partial Hydration
In a standard SPA (e.g., Next.js or Nuxt.js), the entire page must be "hydrated." This means the JavaScript framework must reconstruct the entire DOM in memory to attach event listeners, even for static elements like a header or a footer. This is computationally expensive.

Astro utilizes Partial Hydration.

  1. Static Sea: The majority of the page (Header, Footer, Sidebar, Article Text) is converted to pure HTML and CSS during the build process. No JavaScript is sent for these parts.
  2. Interactive Islands: Dynamic components (like a "Buy" button, a Carousel, or a Dark Mode toggle) are processed separately. The browser downloads the JavaScript only for these specific components.
  3. Parallel Loading: One heavy component (like a complex chart) will not block the rest of the page from being interactive.

How it works in practice:
Imagine a blog post.

  • Header & Footer: Rendered as HTML. No JS.
  • Blog Text: Rendered as HTML. No JS.
  • Comment Section (React Component): Hydrated. The browser loads React and the comment logic only for this specific rectangle of the screen.

πŸ§ͺ Industry Standard:

This architecture was popularized by Katie Sylor-Miller (Etsy) and Jason Miller (Preact). It solves the "Uncanny Valley" of web performance where a page looks ready but doesn't respond to clicks because the main thread is blocked by hydration.


3. Setting Up Your First Astro Project (CLI Magic)

To ensure stability and adherence to current standards, we will use the official CLI tool.

Prerequisites:

  • Node.js: Active LTS version (v18.14.1 or higher).
  • Text Editor: VS Code is recommended (with the official Astro extension).
  • Terminal: PowerShell, Zsh, or Bash.

Step-by-Step Installation:

  1. Launch the Wizard:
    Open your terminal and run the following command. npm will fetch the latest version of the create-astro package.

    bash
    npm create astro@latest
  2. Configure Your Mission (The Prompts):
    The CLI will ask you a series of strict questions. Here is the recommended path for a robust educational setup:

    • Where should we create your new project?
      Type a folder name, e.g., my-astro-site.
    • How would you like to start your new project?
      Select "Include sample files" (Best for learning).
    • Do you plan to write TypeScript?
      Select "Yes". (Industry standard for maintainability).
    • How strict should TypeScript be?
      Select "Strict". (Enforces better code quality).
    • Install dependencies?
      Select "Yes". (This runs npm install for you).
    • Initialize a new git repository?
      Select "Yes".
  3. Lift Off:
    Once the installation completes, navigate into your project folder:

    bash
    cd my-astro-site
    npm run dev

    You will see a message indicating the server is running, typically at http://localhost:4321.
    (Note: 4321 is a countdown... 4-3-2-1 Blast off! πŸš€)


⚠️ Troubleshooting Tip:

If you encounter permission errors during installation, ensure you are not running the command as root or sudo, as this can mess up file ownership in your project directory.


4. Project Anatomy: Understanding the Folder Structure

Astro employs an opinionated folder structure to automate routing and build processes. Understanding the role of src/ vs public/ is critical.

The File Tree:

text
my-astro-site/
β”œβ”€β”€ public/
β”‚   └── favicon.svg
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   └── Card.astro
β”‚   β”œβ”€β”€ layouts/
β”‚   β”‚   └── Layout.astro
β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   └── index.astro
β”‚   └── env.d.ts
β”œβ”€β”€ astro.config.mjs
β”œβ”€β”€ package.json
└── tsconfig.json

Key Directories Explained:

  1. src/pages/ (The Routing Engine):
    Astro uses File-Based Routing.

    • src/pages/index.astro becomes your-site.com/.
    • src/pages/about.astro becomes your-site.com/about.
    • You can also put Markdown (.md) files here, and they will automatically render as pages.
  2. src/components/ (The LEGO Blocks):
    This is where you store reusable UI elements (Buttons, Navbars, Cards).

    • These components are not pages. They cannot be accessed directly via a URL.
    • You import these into your pages.
  3. src/layouts/ (The Wrappers):
    Layouts are special components used to wrap pages. They usually contain the <html>, <head>, and <body> tags. This ensures your header and footer remain consistent across multiple pages.

  4. public/ (The Static Locker):
    Files in this directory are not processed by Astro.

    • They are copied directly to the root of your build.
    • Use this for robots.txt, favicon.ico, or images that do not need optimization.
    • Example: A file at public/images/logo.png is accessible at your-site.com/images/logo.png.
  5. astro.config.mjs (The Control Center):
    This is the configuration file for your project. Here you configure:

    • Integrations: Add React, Tailwind, or Sitemap generation.
    • Server options: Port numbers and host settings.
    • Build options: Output targets (Static vs Server).

🧠 Important Concept: The .astro File

An .astro file is a special file format that looks like HTML but has a "Code Fence" at the top (three dashes ---).

astro
---
// Server-Side JavaScript (Runs ONLY during build/server time)
const pageTitle = "Welcome to Mars";
---
<!-- HTML Template -->
<h1>{pageTitle}</h1>

The code inside the --- fence never reaches the user's browser. It is strictly for data fetching and logic during the build.


References & Further Reading

Challenge

You are tasked with creating a reusable BaseLayout.astro component. This component will serve as the primary layout for all pages on a website, providing a consistent header and page structure.

Your task is to write the complete code for this layout component:

  1. Inside the component script (the code fence ---), define a constant named pageTitle and assign it a string value, for example, "Astro Blog".
  2. Also within the code fence, define an array constant named navLinks. This array should contain at least two objects, with each object having two properties: href (e.g., "/") and text (e.g., "Home").
  3. In the template section (below the code fence), create a full HTML5 document structure (<!DOCTYPE html>, <html>, <head>, <body>).
  4. In the <head>, use the pageTitle constant to dynamically set the content of the <title> tag.
  5. Inside the <body>, create a <header> element. Within this header, dynamically generate an unordered list (<ul>) of navigation links by mapping over the navLinks array. Each list item (<li>) should contain an anchor tag (<a>) whose href attribute and text content are populated from the corresponding object in the array.
  6. Following the <header>, add a <main> element. Inside this element, place a <slot /> tag, which serves as a placeholder for individual page content.

Expected result

Your final code should be a complete .astro component. It must contain a code fence with JavaScript constants for the page title and navigation links, and an HTML template that uses these constants to dynamically render the page's title and navigation menu. It must also include a <slot /> to allow other pages to inject their content into this layout.

astro
---
const pageTitle = "My Personal Blog";
const navLinks = [
  { href: "/", text: "Home" },
  { href: "/about/", text: "About" },
  { href: "/posts/", text: "Blog" },
];
---
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{pageTitle}</title>
</head>
<body>
  <header>
    <nav>
      <ul>
        {navLinks.map(link => (
          <li><a href={link.href}>{link.text}</a></li>
        ))}
      </ul>
    </nav>
  </header>
  <main>
    <slot />
  </main>
</body>
</html>
astro

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.