Astro for Beginners: Getting Started Guide

A comprehensive introduction to Astro web framework for developers new to the ecosystem

Astro Enthusiast

Astro for Beginners: Getting Started Guide

Astro is a modern web framework for building fast, content-focused websites. This guide will help you understand the basic concepts and get started with Astro.

Astro Logo
Astro - The web framework for content-driven websites

What is Astro?

Astro is a web framework that allows you to build faster websites with less client-side JavaScript. It features:

  • Island Architecture: Load only the JavaScript you need
  • Server-first API design: Move expensive hydration off of your users’ devices
  • Zero JS, by default: No JavaScript runtime overhead to slow you down
  • Edge-ready: Deploy anywhere, even global edge runtimes like Deno or Cloudflare
  • Customizable: Tailwind, MDX, and 100+ other integrations to choose from
  • UI-agnostic: Supports React, Preact, Svelte, Vue, Solid, Lit and more

Installation and Setup

Getting started with Astro is easy. You’ll need Node.js installed (version 14.18.0 or higher).

# Create a new project with npm
npm create astro@latest

# Or with yarn
yarn create astro

# Or with pnpm
pnpm create astro

The CLI wizard will guide you through the setup process, offering templates, TypeScript configuration, and more.

Astro CLI setup
Astro CLI setup process

Project Structure

A typical Astro project structure looks like this:

├── public/
│   ├── favicon.svg
│   └── robots.txt
├── src/
│   ├── components/
│   ├── layouts/
│   └── pages/
├── astro.config.mjs
├── package.json
└── tsconfig.json (optional)

Key directories and files:

  • src/pages/: Contains your site’s pages. Each .astro, .md, .mdx, or .html file becomes a route based on its path.
  • src/components/: Where you store your Astro and UI framework components.
  • src/layouts/: Layout components that provide a reusable shell for your pages.
  • public/: Static assets that don’t need processing, like images, fonts, etc.
  • astro.config.mjs: Your project configuration file.

Creating Your First Page

Let’s create a simple page. In src/pages/index.astro:

---
// Component Script (JavaScript)
const pageTitle = "My First Astro Site";
---

<!-- Component Template (HTML + JS Expressions) -->
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{pageTitle}</title>
  </head>
  <body>
    <h1>{pageTitle}</h1>
    <p>Welcome to my website built with Astro!</p>
  </body>
</html>

Astro uses a component-based architecture with a unique file format (.astro) that combines HTML and JSX-like syntax.

Astro component structure
Astro components consist of a script section and a template section

Astro Components

Astro components are the building blocks of your site. They’re defined in .astro files and have two main parts:

  1. The Component Script section (between --- fences) contains JavaScript that runs at build time.
  2. The Component Template section (below the fences) contains HTML and can use variables from the script.

Here’s a simple button component (src/components/Button.astro):

---
// Define props with TypeScript (optional)
interface Props {
  text: string;
  color?: 'primary' | 'secondary';
}

// Access props from the props object
const { text, color = 'primary' } = Astro.props;
---

<button class={`btn ${color}`}>{text}</button>

<style>
  .btn {
    padding: 0.5rem 1rem;
    border-radius: 0.25rem;
    border: none;
    cursor: pointer;
  }
  .primary {
    background-color: #3b82f6;
    color: white;
  }
  .secondary {
    background-color: #d1d5db;
    color: #1f2937;
  }
</style>

Now you can use this component in any page:

---
import Button from '../components/Button.astro';
---

<Button text="Click me!" />
<Button text="Secondary Button" color="secondary" />

Layouts

Layouts help you avoid repeating common page elements. Create a simple layout (src/layouts/MainLayout.astro):

---
interface Props {
  title: string;
}

const { title } = Astro.props;
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{title}</title>
  </head>
  <body>
    <nav>
      <a href="/">Home</a>
      <a href="/about">About</a>
      <a href="/blog">Blog</a>
    </nav>
    <main>
      <slot /> <!-- This is where your content will be inserted -->
    </main>
    <footer>
      <p>&copy; {new Date().getFullYear()} My Astro Site</p>
    </footer>
  </body>
</html>

Use the layout in a page:

---
import MainLayout from '../layouts/MainLayout.astro';
---

<MainLayout title="About Us">
  <h1>About Us</h1>
  <p>We are a team dedicated to building awesome websites with Astro!</p>
</MainLayout>

Content Collections

Astro’s content collections provide a way to organize and validate your Markdown or MDX content. First, define a collection in src/content/config.ts:

import { defineCollection, z } from 'astro:content';

const blogCollection = defineCollection({
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.string().transform(str => new Date(str)),
    author: z.string(),
    image: z.string().optional(),
  }),
});

export const collections = {
  'blog': blogCollection,
};

Then create blog posts in src/content/blog/.

Data Fetching

You can fetch data in the component script section:

---
// Fetch data at build time
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
---

<ul>
  {users.map(user => (
    <li>{user.name}</li>
  ))}
</ul>

Adding Interactivity

Astro ships with zero client-side JavaScript by default, but you can add interactivity with:

  1. Script Tags: For simple JavaScript needs
  2. UI Framework Components: Using React, Vue, Svelte, etc.
  3. Astro Islands: Hydrating only the interactive parts of your page

Example using a React component:

---
import { Counter } from '../components/Counter.jsx';
---

<Counter client:load initial={0} />

The client:load directive tells Astro to hydrate this component as soon as the page loads. Other directives include client:idle, client:visible, etc.

Routing

Astro uses file-based routing:

  • src/pages/index.astro/
  • src/pages/about.astro/about
  • src/pages/blog/index.astro/blog
  • src/pages/blog/[slug].astro/blog/:slug (dynamic route)
File-based routing in Astro
Astro uses a simple file-based routing system that's easy to understand

Deploying Your Astro Site

Astro sites can be deployed to virtually any hosting platform:

  • Static Hosting: Netlify, Vercel, GitHub Pages
  • SSR Hosting: Deno Deploy, Vercel, Netlify
  • Self-Hosted: Docker, Node.js server

For a simple static site deployment to Netlify:

  1. Push your code to GitHub
  2. Connect your repository in Netlify
  3. Use the build settings:
    • Build command: npm run build
    • Publish directory: dist

Learning Resources

Conclusion

Astro’s server-first approach makes it an excellent choice for content-heavy websites like blogs, documentation sites, marketing sites, and portfolios. By shipping only the necessary JavaScript, your sites will load faster and provide a better user experience.

This guide covers the basics, but Astro has many more features to explore, including image optimization, SEO tools, internationalization, and more. Happy coding with Astro!

Enjoy this post?

Check out more articles on our blog to learn more about Foxi theme.

More Articles