How We Cut Astro Build Time from 30 Minutes to 5 Minutes (⚡ 83% Faster!)

 Reducing build times can be a challenging task, especially when working with static site generation (SSG) in frameworks like Astro. Increased build times can have serious consequences, such as delaying small changes from reaching production, sometimes taking several hours to deploy changes across different environments.


We faced this issue while using Astro + React with AWS Amplify, where everything was statically generated (SSG). With over 200+ pages being generated during each build, the process took over 30 minutes on AWS Amplify, which, unlike Vercel, does not support Incremental Static Regeneration (ISR). At one point, a particular section required 900+ pages, further increasing the build times.


As we investigated, we discovered some common mistakes that contributed to these delays. In this blog, we will share optimization techniques that significantly reduced our build times.


Avoid API Calls in Child Components

One of the key issues we identified was related to API calls in child components within the [slug].astro file. In Astro, slugs are generated using getStaticPaths, which is executed once to fetch all the data required for generating pages.


However, if a child component inside [slug].astro includes an API call to fetch data for the component, the request will be triggered individually for each page when the page is being generated. For example, if the request takes 300ms to resolve, the build time for that page will be 300ms plus the actual time required to build the page. Now, imagine your site has 100 pages under this slug—this means the API calls alone would add 30 seconds (100 × 300ms) to your total build time, even before considering other processing delays, thus significantly increasing build times from milliseconds to seconds per page.


Solution


Avoid making API calls in child components whenever possible. Instead, pass data via props to ensure that the component does not make unnecessary API calls to fetch data.

If an API call is necessary, use client:only="{framework}". This skips server-side HTML rendering and ensures the component renders only on the client. In place of {framework}, specify the correct framework for the component. Since Astro does not execute the component during the build or on the server, it needs explicit information about the framework being used. Alternatively, you can use the <script> tag within the Astro component to run JavaScript for API calls on the client side.



Comments

Popular posts from this blog

Serverless Architecture: A Game Changer for Enterprises and Startups

React Router v7 vs Remix: Understanding the Evolution and What to Use

Beyond Caching: Unconventional Strategies to Achieve Millisecond Latency