Rebuilding My Blog with Astro

Posted on 16 July 2024 Reading time: 7 min read
Rebuilding My Blog with Astro

Transitioning from an outdated platform to a modern, efficient one can be a daunting task. This was my reality when I decided to rebuild my blog. Previously, my blog was built with Gridsome, a framework I cherished for its simplicity and performance. However, development on Gridsome slowed significantly, and to compound issues, Forestry.io, the CMS I used, was acquired and rebranded. With these challenges, I embarked on a journey to find a new solution that would meet my needs. After exploring various options like Nuxt and Next.js, I was introduced to Astro. This is the story of how I rebuilt my blog with Astro.

The Search for a New Framework

When it became clear that Gridsome was no longer being actively developed, I knew I had to move on. I needed a modern framework that could handle static site generation and offer great performance. I first explored Nuxt, a powerful and flexible framework that seemed promising. Next.js was another contender, known for its server-side rendering and static site generation capabilities. Both were impressive, but they came with a learning curve and complexity I wasn’t ready to tackle.

Discovering Astro

Enter Astro. I was chatting with one of my friends about my search for a new framework to rebuild my blog with. She mentioned Astro and I decided to have a go at it. I learnt that Astro promises to deliver faster websites by default, focusing on performance and simplicity. It allows you to build sites with your favorite frameworks like React, Vue, or Svelte, but only ships the minimal amount of JavaScript needed. Having developed with Vuejs for many years, this sounded like the perfect solution for my needs.

Quick Astro Primer

To get started with Astro, follow these installation steps and basic setup guidelines.

Installation Steps

  1. Install Node.js: Make sure you have Node.js installed. You can download it from Node.js. Make sure you have the latest version of Node.js installed. One of the gotchas I tripped on was my version being less than v20.

  2. Create a New Astro Project: Run the following command in your terminal to create a new Astro project:

    npm create astro@latest
    

    Follow the prompts to set up your project.

  3. Navigate to Your Project Directory: Change into the newly created directory:

    cd your-project-name
    
  4. Install Dependencies: Install the required dependencies using:

    npm install
    
  5. Run the Development Server: Start the development server to see your project in action:

    npm start
    
  6. Build Your Project: Once you are ready to deploy, build your project with:

    npm run build
    

Setting Up a Blog with Astro

Here’s a quick guide to setting up a blog with Astro, including generating content from Markdown files and managing content collections.

Generating Content from Markdown Files

  1. Create a Content Directory: Create a content directory in the root of your project and add a blog folder inside it. This is where your Markdown files will reside.

  2. Add a Sample Markdown File: Create a sample blog post in content/blog:

    ---
    title: "My First Blog Post"
    description: "Welcome to my new blog!"
    pubDate: "2024-07-16"
    author: "Your Name"
    ---
    
    This is the content of my first blog post.
    
  3. Configure Content Collections: In your src/content/config.ts file, define your blog collection:

    import { defineCollection, z } from 'astro:content';
    
    const blogCollection = defineCollection({
      schema: ({ image }) => z.object({
        title: z.string(),
        description: z.string(),
        author: z.string(),
        pubDate: z.coerce.date(),
        updatedDate: z.coerce.date().optional(),
        heroImage: image().optional(),
      }),
    });
    
    export const collections = { 
      blog: blogCollection 
    };
    
  4. Fetch and Display Blog Posts: In a new file src/pages/blog/[slug].astro, fetch and display your blog posts:

    ---
    import { getCollection, type CollectionEntry } from 'astro:content';
    import BlogPostLayout from '../../layouts/BlogPostLayout.astro';
    
    export async function getStaticPaths() {
      const posts = await getCollection('blog');
      return posts.map((post) => ({
        params: { slug: post.slug },
        props: { post },
      }));
    }
    
    const { post } = Astro.props;
    const { Content } = await post.render();
    ---
    
    <BlogPostLayout {...post.data}>
      <Content />
    </BlogPostLayout>
    

Benefits of Astro’s Image Component

One of the standout features of Astro is its Image component. This component brings several benefits that enhance the performance and user experience of my blog:

  • Automatic Image Optimization: Astro’s Image component automatically optimizes images for various screen sizes and resolutions. This means that users get the best quality images without unnecessary data, resulting in faster load times.

  • Responsive Images: With the Image component, you can easily define different image sizes for different devices. This ensures that the appropriate image size is served based on the user’s device, further improving load times and reducing bandwidth usage.

  • Lazy Loading: Images are lazy-loaded by default, which means they only load when they come into the viewport. This improves the initial load time of the page and provides a smoother user experience.

  • Modern Image Formats: Astro supports modern image formats like WebP, which offer better compression and quality compared to traditional formats like JPEG and PNG. This further enhances performance and reduces the size of images served to users.

Integrating Astro’s Image component into my blog was straightforward and provided immediate benefits in terms of performance and user experience.

The Sharp Issue

One significant issue I encountered during the rebuild was with the sharp image processing library. In my local environment, I had to run yarn add sharp --ignore-engines to get images to render correctly. This step ensured that sharp was installed despite any engine incompatibilities.

However, in production, I kept hitting the error: “Could not process image request: MissingSharp: Could not find Sharp.” This was particularly frustrating because sharp was already installed locally. After some troubleshooting, I decided to replicate the local workaround in the production build process.

I use Coolify to build and deploy my blog. I added the following to the Coolify build command field: yarn install & yarn add sharp --ignore-engines. And voila! It worked! This experience taught me the importance of ensuring that all necessary dependencies are correctly installed in the production environment. I believe this should be documented and hope it helps anyone who encounters this problem.

Deploying with Coolify

Deployment was another area where I needed a robust solution. I decided to use Coolify, a self-hosting platform that simplifies deployment and continuous integration. Coolify made it possible to deploy my Astro site effortlessly and automatically apply changes whenever I pushed updates to my repository.

Coolify provided a seamless deployment experience:

  • Self-Hosting: With Coolify, I could host my site on my own server, giving me full control over the deployment environment.
  • Automatic Deployments: Every time I pushed changes to my Git repository, Coolify detected the updates and redeployed my site, ensuring that my blog was always up-to-date.

The Result

After a few days of learning and building, my blog was fully transitioned to Astro. The results were impressive:

  • Improved Performance: Astro’s performance optimizations, along with the benefits of its Image component, were evident. My site loaded faster, providing a better experience for my readers.
  • Simplified Content Management: Managing content with Astro’s collections was intuitive and efficient.
  • Seamless Deployment: Coolify made the deployment process painless, allowing me to focus on creating content rather than managing infrastructure.

Rebuilding my blog with Astro was a rewarding experience. Despite the initial learning curve, Astro’s simplicity, performance benefits, and flexibility made it an excellent choice for my needs. Combined with the power of Coolify for deployment, I now have a modern, efficient blog that I can easily manage and update.

If you’re looking to transition from an older platform or simply want to explore new possibilities for your static site, I highly recommend giving Astro a try. And if you encounter issues with sharp, remember the trick: yarn install & yarn add sharp --ignore-engines can save you a lot of frustration. The benefits of Astro’s Image component also make it an attractive option for anyone looking to optimize their site’s performance and user experience.