GSD

What is Astro? A Quick 2-Minute Introduction to Astro JS

Posted by Maab Saleem on December 13, 2023

Astro is an open-source, server-first web framework that combines the best of static site generation (SSG) and server-side rendering (SSR) to create fast, SEO-friendly websites. Astro is purpose-built to power content-rich websites and boasts a comprehensive development ecosystem.

In this post, we will offer a brief overview of Astro, covering its design, benefits, and initial setup.

Astro is a faster, lighter, HTML-first framework

Astro doesn’t include JavaScript code in its output by default. It strips away all the JavaScript at build time, resulting in pure, lean HTML and CSS. Another great thing about Astro is its framework-agnostic nature – You can build UI components using various libraries and frameworks, including React, Vue, Svelte, and Preact. 

It’s possible to import and render components from different frameworks in the same file. Even nesting different framework components is supported. For instance, you can seamlessly do something like this:

import ReactComponent from './ReactComponent.astro';

import VueComponent from './VueComponent.astro';

import AlpineComponent from './AlpineComponent.astro';

<VueComponent>

  // A React Component inside a Vue component

  <ReactComponent />

</VueComponent>

<AlpineComponent />

In this code snippet, a Vue component (VueComponent) wraps a React component (ReactComponent), whereas an Alpine component (AlpineComponent) is rendered independently. 

The true magic of Astro lies in its ability to deliver this multi-component flexibility without augmenting the bundle size (because there’s no JavaScript). It’s like having the freedom to use a combination of your favorite tools without worrying about interoperability or performance.

Learn how ButterCMS can revolutionize your content management.
Start my free trial

Customizing Astro with JavaScript 

Even though Astro is HTML-first, it doesn’t restrict you from customizing with JavaScript wherever necessary. In this context, JS Customization means using JavaScript to add interactivity to your app.

This is achieved through the concept of islands; self-contained, interactive components that float within a sea of static HTML. 

It’s JavaScript but without the performance drag.

To convert any component into an interactive Island, you can use the client:* directive. This directive instructs Astro to bundle the client-side JavaScript associated with the component. 

Since this directive is being set at the component level, it becomes easy to set loading priorities. For instance, you can use client:load to load an island at the initial page render, client:idle to load when the main thread is available, or client:visible to load when the island becomes visible to the user.

<MySvelteComponent client:idle />

The above line sets the component MySvelteComponent to load only when the main thread is idle and not immediately when the page loads. 

More reasons to love Astro

Astro is a truly modern web framework that offers several benefits, including:

  • The perfect blend of speed and interactivity: Astro strikes a delicate balance between speed and dynamism. HTML-first principles ensure inherently faster load times, whereas islands enable developers to infuse interactivity into their apps wherever required. 

  • Developer-friendliness: Astro is designed to democratize web development. The .astro UI language is a superset of HTML, meaning anyone familiar with HTML can easily write Astro components. Moreover, it offers a robust CLI tool, TypeScript support, and a diverse collection of plugins and integrations. Furthermore, since it’s open-source, you can tailor any aspect of the framework to suit specific application requirements.  

  • SEO by default: Since static HTML pages are notably easier for search engines to crawl and index, Astro sites typically rank higher than those built with JavaScript-heavy frameworks. This leads to increased visibility and organic traffic.

  • A rich feature set: Astro offers several advanced features out of the box. For example, the built-in image package simplifies the lazy loading of images sourced from a CMS or a CDN. Additionally, its internationalization routing features make it easy to manage and display multilingual content. 

  • Minimal configuration, maximum flexibility: With sensible defaults and minimal setup, Astro allows developers to focus on building without getting bogged down by complex configurations. However, it offers extensive customization options for those looking to fine-tune. For example, you can configure Astro to disable HTML compression, customize output file format, or define custom image endpoints.

  • Parallel loading: Astro’s architecture allows for the simultaneous loading of multiple islands without one impeding the other. For example, lower-priority islands, like a “recent posts” section won’t hinder the loading of higher-priority islands, such as the header. This ensures that the most important elements can load and become interactive immediately.

Setting up your first Astro project

To create a new Astro project using npm, run this command:

npm create astro@latest

If you prefer yarn, you can use this command:

yarn create astro

After the command completes, you should see a new directory created for your project. 

Creating a project using a starter template

Alternatively, you can create an Astro project using a starter template. On the official GitHub repository, you will find starter templates for blogs, React projects, Vue projects and more. The command to instantiate a project with a starter template using npm is:

npm create astro@latest -- --template <name-of-the-example>

And with Yarn:

yarn create astro --template <name-of-the-example> 

Understanding the directory structure

In the auto-generated project directory, you should see the following files and folders:

public/

This folder holds static assets like images and fonts that are not processed by Astro.

src/

This folder contains the source code for your project across these subfolders: components, layouts, pages, and styles. 

tsconfig.json

This file configures the TypeScript support for your project.

package.json

This file defines metadata about your project, including its name, version, dependencies, and scripts. 

astro.config.mjs

This file configures Astro for your project’s specific needs. 

Starting the development server

Astro ships with a default development server that you can run to serve your website locally. To start the server using npm, use this command:

npm run dev

Or with yarn, run:

yarn run dev

You should now be able to see your site in action at http://localhost:4321/

Astro actively monitors changes made within your project's src/ directory and instantly applies them without needing a restart.

Adding a framework

Integrating a UI framework into your project is as simple as running a CLI command. For example, you can add React to an Astro project using this command:

npm astro add react

Or with Yarn:

yarn astro add react

Structuring your component

An Astro component comprises two blocks: the component script and the component template

The component script, delineated by a code fence (---), encapsulates the JavaScript logic for your component. You can use it to import other components, fetch data from external sources, or define props. The component template contains your HTML and any JavaScript expressions you want to define. 

Let’s look at a sample component file for a better understanding:

// Component Script

---

import OtherComponent from './OtherComponent.astro';

import { fetchData } from './utils';

const someVariable = 'Astro';




const { prop } = Astro.props;

const data = await fetch(`http://some-api/users`).then(r => r.json());

---




<!-- Component Template -->

<div>

  <h1>Hello, {someVariable}</h1>

  <OtherComponent prop={prop} data={data} />

</div>

This snippet shows an Astro component script and template. The script imports an external component (OtherComponent.astro) and a fetchData function from a utils file. It defines a variable someVariable, uses Astro.props to access props, and then fetches data from an external API. 

The template then uses these elements to display a greeting using someVariable, and renders OtherComponent with the props and data.

Final thoughts

Astro is a feature-rich, modern web framework with a rapidly evolving ecosystem and community. It enables developers to leverage a combination of frontend frameworks to build HTML-first, static websites with minimal use of client-rendered JavaScript. In this brief read, we offered a concise yet comprehensive overview of Astro; we hope you found it insightful.

Additional resources for learning Astro

Official Astro docs

Astro on GitHub

Astro configuration reference

The best CMS for Astro

Astro blog engine

Build a knowledge base with Astro and ButterCMS

Make sure you receive the freshest tutorials and Butter product updates.
Maab Saleem

Maab is an experienced software engineer who specializes in explaining technical topics to a wider audience.

ButterCMS is the #1 rated Headless CMS

G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award

Don’t miss a single post

Get our latest articles, stay updated!