guus van de wal
Menu

Unlocking Faster Websites with Astro: Streamlining Image Management from Strapi

19 March 2024

I've primarily used frameworks like Next.js and Vue.js for my projects. However, Astro has recently captured my attention due to its exceptional build speeds, flexibility in utilizing various frameworks, and overall efficiency. While I initially encountered challenges with dynamically managing images stored in my Strapi backend (including minimizing, editing, and deleting them), Astro's powerful astro-imagetools library proved instrumental. This library enables the automatic rendering of optimized images within my Strapi dynamic components, eliminating the need for manual optimization.

Key Benefits of Astro and Image Optimization:

  • Enhanced Performance: Astro delivers lightning-fast build times and website rendering, ensuring a smooth user experience.
  • Streamlined Image Management: Seamless integration with Strapi offers centralized image storage and manipulation.
  • Automatic Image Optimization: The astro-imagetools library simplifies image optimization, ensuring optimal loading times and improved SEO.
null

Code Syntax Block tsx

// Import the renderImg function for image optimization
import { renderImg } from "astro-imagetools/api";

let image; // Variable to store image data
let imageHTML; // Variable to store optimized image HTML

// Define the base URL for your Strapi API
const baseURL = import.meta.env.ASTRO_STRAPI_URL;

// Check if the component is an image component from Strapi
if (paragraphs.__component === "paragraphs.image") {
  image = paragraphs.Image.data.attributes; // Extract image data

  // Optimize image using renderImg()
  imageHTML = await renderImg({
    src: baseURL + image.url, // Construct image URL
    alt: image.alternativeText,  // Include image alt text
    decoding: "async", // Enable asynchronous image loading
  });
}

// Conditionally render the optimized image
{
  image && (
    <>
      <div set:html={imageHTML.img} />
    </>
  )
}