Astro is one of my new favorite tools for building anything from blogs to full-fledged web apps. I’m particularly drawn to features like file-based routing, the island architecture, and the option to choose between static generation and server-side routing. In this tutorial, I’ll help you get set up with a basic blog.
Getting started
To get started, run the setup wizard! 🧙
The wizard does a nice job of guiding you through the setup process. You can even skip reading the rest of this post and choose Use blog template
in the wizard to use Astro’s default blog template. For this post, I instead chose the option Include sample files
.
Below you can see all the options I chose:
To ensure the wizard worked properly, cd
into your project and run:
You should be up and running now!
Updating the home page
As of astro@3.0.8
, the create command generates the following files under src
:
Assuming that you have the same files in your src
directory*, add some default styling to the layout:
From there, update the index page to the following:
Now view the site in your browser, and you should see a simple blog homepage. Next, let’s make that link on the homepage work!
Adding posts
Your simple homepage introduced a link to a blog index, which doesn’t exist yet, so let’s add the blog index and post pages to make the link work.
First, create these directories:
After that, create these files:
From there:
- Create a simple post…
- Update
src/pages/posts/[slug].astro
to show the post…
- Update
src/pages/blog/[page].astro
to list paginated posts…
What just happened!?
We went over that rather quickly, so let’s recap:
- We created content for a post.
- We created a way to view a post.
- We created a way to view all posts.
The real magic ✨ here happened with the introduction of the getStaticPaths
and getCollection
functions. getStaticPaths
allows us to use dynamic routes so that we can display any post with our [slug].astro
page, or paginate posts with our [page].astro
page. getCollection
allows us to easily grab and transform our blog content for consumption. Using these 2 functions together is a real win-win! 🎉
Wrapping up
Obviously, this is a pretty simple example, and you would want to add more styles and pagination links and navigation, etc. etc. BUT hopefully you were able to experience some of the benefits of Astro and learn a little along the way.
* If you are using a different version of Astro, or if anything doesn’t make sense, you can view the full example code here.