1. javascript
  2. /frameworks
  3. /astro

Web Frameworks - Introduction to Astro

Astro is rapidly gaining industry recognition for its emphasis on performance and flexibility. With that in mind, we aim to provide you with a comprehensive enough understanding of Astro's core concepts and features. By the end of this article, you'll have the insights needed to experiment with it for personal projects or consider it a viable option for your professional endeavors.

What is Astro and Why Use It?

The framework distinguishes itself through a server-first approach, focusing on speed and SEO via static HTML pages. This strategic direction sets it apart from more client-side JavaScript-dependent frameworks. It excels in content-rich scenarios like blogs, portfolios, and certain types of e-commerce sites. Beyond this, Astro contains innovative features such as "Island Architecture" and a broad array of integrations.

Key Features

First, let's delve into the features that make Astro truly unique.

  • Component Islands: The framework allows you to construct your site using isolated, interactive components, thereby improving speed by only loading JavaScript where it's needed.

Additional historical and technical context on Islands Architecture

  • Server-first API Design: In web development, "hydration" typically refers to the process of adding client-side interactivity to a static HTML page. This framework shifts the responsibility to the server, minimizing initial load and interaction time on the client side.

  • Zero JS, By Default: The JavaScript sent to the browser is minimized, thereby reducing load times and improving user experience.

Why Choose This Framework?

There are several compelling reasons to consider Astro, each contributing to a potentially faster and more efficient web development process.

  • Content-focused: With a design optimized for content-heavy websites like blogs and portfolios, Astro excels where content delivery is the priority.

  • Performance: By combining server-side rendering and partial hydration, the framework achieves superior speed without sacrificing functionality.

  • Flexibility: Astro's agnostic approach to frameworks enables integration of components from React, Vue, and Svelte, freeing you from tech stack limitations.

However, for web applications requiring complex interactivity, you might find more application-centric frameworks like Next.js—or others designed with complex applications in mind—to be better suited for your needs.

Getting a Feel of Astro

Whether you're just curious or seriously considering the framework for your next project, there are multiple ways to get started. You can try Astro in your browser for a quick experience, or set up a local development environment for more in-depth exploration.

Try Astro Online

If you're keen to explore Astro without any local setup, your quickest option is astro.new. This official portal provides a variety of starter templates that allow you to quickly grasp Astro's capabilities.

Inside it, you'll find templates for basic setups, content-focused websites like blogs and portfolios, as well as templates pre-configured for popular frameworks like React, Vue, Svelte, and Solid among others. Additionally, they even offer templates for specific integrations, such as Tailwind CSS and Markdown, and more advanced use cases like Server-Side Rendering.

By default, these templates open in StackBlitz, an online code editor that lets you modify and run projects directly in your browser. However, you're not limited to StackBlitz; you can choose to open these templates in other online code editors like CodeSandbox or Gitpod, or even view the source code on GitHub to get a deeper understanding.

Setting Up Astro Locally

If you're looking to work with Astro on your own machine, you have two avenues: an automated setup via Astro's CLI or a more hands-on, manual configuration.

The create astro CLI tool is your fastest way to a new Astro project. Depending on your package manager, you can run one of the following commands:

# With npm
npm create astro@latest

# With pnpm
pnpm create astro@latest

# With yarn
yarn create astro

With this, you initiate a somewhat interactive setup, even offering you a choice of starter templates for different project types. To delve into the details, consult the automated installation guide.

A manual setup gives you full control over your project's configurations. This process involves creating a directory, initializing a package.json, and manually installing Astro. You'll also configure your first Astro page and handle static assets. Further customization options like astro.config.mjs and TypeScript support are available. For a step-by-step guide, visit the manual installation documentation.

Before you begin, make sure you have Node.js v18.14.1 or higher installed, a text editor (VS Code is recommended and has an official Astro extension), and terminal access.

Astro Fundamentals: Project Structure and Syntax

Next, we'll observe a snapshot of Astro's foundational elements: its project structure, unique syntax inspired by HTML and enriched with JSX-like capabilities, and basic illustrations to bring these concepts to life. However, we won't cover every nuance; for that, you'll want to consult Astro's extensive documentation.

Project Structure

When you generate a new Astro project using the create astro CLI command, you'll find that some files and folders are automatically created for you. As your project evolves, you may also manually add additional files to this existing structure.

In an Astro project, you'll find a set of opinionated, yet flexible, directories and files. Here are the core elements you should be aware of:

  • src/: This directory is where most of your project's source code resides. It contains essential subdirectories like src/pages/, necessary for defining your site's pages, and src/components/, where reusable Astro components are stored.

  • public/: Files in this directory are not processed during Astro's build phase, making it ideal for static assets like images, fonts, or configuration files such as robots.txt.

  • package.json: This file acts as the project manifest and is where you manage dependencies and scripts. Both dependencies and devDependencies are used, with Astro requiring all dependencies at build time.

  • astro.config.mjs: While not mandatory, this file is highly recommended. Generated in every starter template, it centralizes various configuration options for your Astro project.

  • tsconfig.json: This TypeScript configuration file is also created by default in starter templates and is necessary for features like npm package imports in your editor.

Among the src/ subdirectories, only src/pages/ is strictly required for Astro to function; it is indispensable for setting up your site's pages and routes. The other directories like src/components/ and src/styles/ are conventions you're free to adapt.

Astro also has a src/content/ directory reserved for content collections and a src/layouts/ directory for Astro components that define shared UI structures across pages.

While this captures the basics, you're free to rename and reorganize these directories as you see fit, except for src/pages/.

The Astro Syntax - Rich Yet Familiar

If you're versed in HTML, you'll find Astro's syntax intuitive. It builds upon HTML, incorporating JSX-like elements to offer a broader set of capabilities for crafting components.

Astro components feature a "frontmatter" section, enclosed within triple dashes (---). This specialized script section allows you to declare local variables, accessible within your HTML template through curly brace syntax {}.

const welcomeMessage = "Welcome";

<!-- The following line will render as <h1>Welcome to the universe!</h1> -->
<h1>{welcomeMessage} to the universe!</h1>

It's crucial to note that these local variables, while dynamic during rendering, become static once the page is generated. They are not reactive and won't update during client-side interactions.

Local variables can also dynamically set attributes in HTML elements. However, be aware that these attributes are converted to strings. For attaching functions or event handlers, you'll need to employ client-side scripts post-rendering.

In addition, the framework supports complex expressions within curly braces, including conditional logic and iterations, enabling the crafting of dynamic HTML content directly within your HTML template. For those interested in the nitty-gritty, the official documentation provides more comprehensive insights.

Commenting is also versatile. You can use traditional HTML comments, which are visible in the final DOM or opt for JavaScript-style comments, which are excluded.

<!-- This is an HTML comment, visible in the final DOM. -->
/* This is a JavaScript-style comment, excluded from the final DOM. */

Distinguishing itself from JSX, Astro allows kebab-case for HTML attributes and doesn't require a single root element. Fragments can also be used for grouping elements without adding extra nodes to the DOM.

Astro syntax, enriched with JSX-like capabilities, is part of a bigger picture. In a typical project, you'll find specific directories for components, pages, and layouts, allowing you to organize your code effectively. Each of these foundational structure elements has a unique role, giving you granular control over the rendering process.

Wrapping Up

We've navigated through some of Astro's key features, from its server-first approach to its unique syntax, equipping you with the foundational understanding to confidently explore or adopt the framework. If you're intrigued, we recommend keeping an eye on its evolving capabilities. The recent features introduced in Astro 3.0 offer a glimpse into the dynamic future of this innovative framework.

Additional Resources

The Offical Astro Website

Astro Discord Community

Astro on GitHub

Astro's X (Twitter) Account