Astro Introduction Guide For Beginners
Learn how to create efficient and fast websites with Astro, the web framework for content-driven websites

September 1, 2024
Table of Contents
Chapter 1: Introduction
What is Astro?
Astro is a an open-source web framework, is very customizable and itβs built with performance in mind. Itβs a great tool for building static sites, blogs, and even dynamic web applications.
Init a new Astro project
To create a new Astro project, you can use the following command:
npm create astro@latest
Some questions will be asked, after that, the project will be created. You can follow the example below:
Structure of an Astro project
An Astro new project has the following structure:
.βββ README.mdβββ astro.config.mjsβββ package-lock.jsonβββ package.jsonβββ publicβ βββ favicon.svgβββ srcβ βββ componentsβ β βββ Card.astroβ βββ env.d.tsβ βββ layoutsβ β βββ Layout.astroβ βββ pagesβ βββ index.astroβββ tsconfig.json
Layout
Astro uses a layout system to define the structure of the pages. It can be re-used in other parts of application, where a developer wants to use the same page layout.
---interface Props { title: string;}
const { title } = Astro.props;---
<!-- src/layouts/Layout.astro --><!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="description" content="Astro description" /> <meta name="viewport" content="width=device-width" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="generator" content={Astro.generator} /> <title>{title}</title> </head> <body> <slot /> </body></html><style is:global> :root { --accent: 136, 58, 234; --accent-light: 224, 204, 250; --accent-dark: 49, 10, 101; --accent-gradient: linear-gradient( 45deg, rgb(var(--accent)), rgb(var(--accent-light)) 30%, white 60% ); } html { font-family: system-ui, sans-serif; background: #13151a; } code { font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace; }</style>
Letβs see some elements that we can find:
Component Script
(---): Allows to import other Astro components, framework components, data, fetching, create variables, receive props, etc.HTML
: After the component script, the HTML structure is defined.<slot />
: Itβs a placeholder for the content of the page.<style is:global>
: Itβs a global style that will be applied to all the pages derived from this layout. Astro was designed to make styling and writing CSS a breeze, you can write your own CSS directly inside of an Astro component.
Pages
Astro uses the .astro
extension for its components. The pages are the main components of the application, they are the ones that will be rendered in the browser.
Replace the content of the index.astro
file with the following code:
---import Layout from "./layouts/Layout.astro";---
<!-- src/pages/index.astro --><Layout title="Astro Guide"> <h1>Welcome to Astro Introduction Guide For Beginners</h1> <p>Learn how to create efficient and fast websites with Astro.</p></Layout>
<style> h1 { color: rgb(var(--accent)); }
p { color: white; }</style>
Run the project
To test the project, you can use the following command (using the terminal):
npm run dev
Your terminal will show the following message:
The project will be running on http://localhost:4321
.
Components
Components allow us to split the UI into independent and reusable pieces of code. They can be used in different parts of the application.
Change the content of the Card.astro
file with the following code:
---interface Props { title: string; description: string;}
const { title, description } = Astro.props;---
<!-- src/components/Card.astro --><article> <h2>{title}</h2> <p>{description}</p></article>
<style> article { background: rgb(var(--accent-light)); padding: 1rem; border-radius: 0.5rem; margin: 1rem 0; }
h2 { color: rgb(var(--accent)); }
p { color: rgb(var(--accent-dark)); }</style>
We can define the props that the component will receive, in this case, the Card
component will receive a title
and a description
. The values of the props are extracted from the Astro.props
object.
You can render the props in the component using curly braces {}
.
If you want to use the Card
component in the index.astro
file, you can import it and use it like this:
---import Layout from "./layouts/Layout.astro";import Card from "./components/Card.astro";---
<!-- src/pages/index.astro --><Layout title="Astro Guide"> <h1>Welcome to Astro Guide For Beginners</h1> <p>This is a guide to learn how to use Astro.</p> <Card title="Card Title" description="Card Description" /></Layout>
<style> h1 { color: rgb(var(--accent)); }
p { color: white; }</style>
Routing
Astro uses the file system to define the routes of the application.
For example, if you want to create a new page called about.astro
, you can create a new file in the src/pages
directory called about.astro
:
---import Layout from "./layouts/Layout.astro";---
<!-- src/pages/about.astro --><Layout title="About"> <h1>About</h1> <p>This is the about page.</p> <a href="/">Go back home</a></Layout>
<style> h1 { color: rgb(var(--accent)); }
p { color: white; }</style>
The about.astro
file will be available at http://localhost:4321/about
.
To go back to the home page, you can use the <a href="/">Go back home</a>
tag.
Chapter 2: Astro Islans
What is Astro Islands?
An interactive UI component. Multiple islands can exist on a page, and each island can use any UI framework, or even just plain Astro code.
Using React with Astro
The Astro integrations are very easy to install and use. For integrate React with Astro, you can use the following command:
npx astro add react
The terminal will show the following messages:
Run the project again:
npm run dev
Next, create the file ReactComponent.jsx
in the src/components
directory and after that, add the following react component to the file:
const Hello = () => { return <h1 style={{ color: "green" }}>Hello from React!</h1>;};
export default Hello;
Next you can import the new React component in the index.astro
file:
---import Layout from "./layouts/Layout.astro";import Card from "./components/Card.astro";import ReactComponent from "./components/ReactComponent.jsx";---
<!-- src/pages/index.astro --><Layout title="Astro Guide"> <h1>Welcome to Astro Guide For Beginners</h1> <p>This is a guide to learn how to use Astro.</p> <Card title="Card Title" description="Card Description" /> <ReactComponent client:load/></Layout>
<style> h1 { color: rgb(var(--accent)); }
p { color: white; }</style>
Add the client:load
attribute to the React component to make sure itβs only rendered on the client side.
Chapter 3: API Endpoints
What is Astro Endpoints?
Are custom endpoints to serve any type of data to the client. They can be used to fetch data from a database, an external API, or any other source.
Using Astro Endpoints
You will need to create a new file in the src/pages/api
directory. Next, create a file called data.json.ts
and add the following code:
export async function GET() { return new Response( JSON.stringify({ message: "Hello from the API!" }) )}
You can consume the data from the endpoint in the ReactComponent.jsx
file that we created earlier:
Replace the content of the ReactComponent.jsx
file with the following code:
import { useEffect, useState } from "react";
const Hello = () => {
const [data, setData] = useState(null);
useEffect(() => { fetch("/api/data.json") .then((res) => res.json()) .then((data) => { setData(data); }); }, []);
return ( <> <h1 style={{ color: "green" }}>Hello from React!</h1>; <p style={{ color: "yellow" }}>{data ? data.message : "Loading..."}</p> </> )};
export default Hello;
If you want to see in the browser the message from the API, check the url http://localhost:4321/api/data.json
, the data will be displayed using json format. This is beacuse in the name of the file we have the .json
extension to indicate the response format.
Build and Preview the Project
To build the project, for production, you can use the following command:
npm run build
This command will generate a dist
directory with the production build of the project.
Inside the dist
directory, you can see multiple static files inlcuding the index.html
file and the other pages. If you check the API folder you will see the data.json
file with the data that we created.
Next, stop the development server using Ctrl + C
and run the following command:
npm run preview
This command will start a local server similar to the npm run dev
command (in the same port), but it will serve the production build of the project.
Conclusion
Astro is a very complete technology, we have a very simple routing system for beginners, and the syntax is incredibly simple!
I hope you found this guide useful, that you can start using Astro in your projects and that you can go deeper into more advanced topics.
If you have any questions, feel free to ask via social media.
Happy coding!
References
- Getting started | Docs. (n.d.). Astro Docs. Retrieved September 1, 2024, from https://docs.astro.build
- Vue.js. (n.d.). https://vuejs.org/guide/essentials/component-basics.html
- Drugalya, O. (2020, November 17). Layout Component and why we use it in React. DEV Community. https://dev.to/olenadrugalya/layout-component-and-why-we-use-it-in-react-d8b