Migrating from Gatsby to Astro

Gatsby shaped a generation of React-based content sites: GraphQL for data, plugins for everything, and a full React application hydrated on every page. Many of those sites are now in an awkward place — long builds, a heavy JavaScript bill for pages that are mostly text, and a plugin ecosystem that has slowed down. Astro is the natural destination for them. It keeps React for the parts that need it, renders everything else to plain HTML, and replaces GraphQL with typed content collections.

This guide migrates a 900-page Gatsby 5 marketing and blog site to Astro 5 in five steps, and measures build time, JavaScript and Core Web Vitals before and after. It follows the playbook in Migrating Between Static Site Generators; the alternative destination for Gatsby sites is covered in Migrating from Gatsby to Next.js Static Export.

Prerequisites

  • The Gatsby site's source, a list of plugins in gatsby-config.js, and its production URL list (from public/sitemap-*.xml or a crawl).
  • Node.js 20 or later.
  • A decision on interactive components: which truly need client-side JavaScript. Usually a handful.

Step 1: Map Plugins to Astro Equivalents

Gatsby sites are defined as much by plugins as by code. Map each before moving anything:

Gatsby pluginAstro equivalent
gatsby-source-filesystem + gatsby-transformer-remark / gatsby-plugin-mdxcontent collections + @astrojs/mdx
gatsby-plugin-image / gatsby-imageastro:assets <Image> / <Picture>
gatsby-plugin-react-helmet<head> in a layout component
gatsby-plugin-sitemap@astrojs/sitemap
gatsby-plugin-feed@astrojs/rss
gatsby-plugin-manifest, -offlinea static manifest; drop the service worker unless needed
gatsby-remark-prismjsbuilt-in Shiki highlighting
gatsby-plugin-google-gtaga deferred first-party script or Partytown
gatsby-source-contentfula loader in the content layer, or fetch at build time

The offline plugin deserves a decision rather than a port: service workers from old Gatsby sites often cause more stale-content bugs than they prevent, and dropping one requires shipping a self-unregistering worker for a few months so existing visitors' browsers clean up.

Gatsby's architecture compared with Astro's Gatsby: sources feed a GraphQL data layer, page queries fetch data, React renders HTML, and the full React app plus page data JSON is hydrated in the browser. Astro: content collections are queried with getCollection, Astro components render HTML, and only components with a client directive ship JavaScript as islands. Same content, different runtime story Gatsby source plugins GraphQL layer React SSR full app hydrated Astro collections getCollection() Astro + React SSR only islands hydrate React components move across largely unchanged; what disappears is the default hydration
The migration keeps the components and drops the runtime most pages never needed.

Step 2: Replace GraphQL Queries With Collections

A typical Gatsby blog template queries MDX nodes with GraphQL. In Astro, the same data comes from a typed collection:

// Gatsby: src/templates/post.js (excerpt)
export const query = graphql`
  query($id: String!) {
    mdx(id: { eq: $id }) { frontmatter { title date(formatString: "MMM D, YYYY") hero { childImageSharp { gatsbyImageData(width: 1200) } } } body }
  }`;
---
// Astro: src/pages/blog/[...slug].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
export async function getStaticPaths() {
  const posts = await getCollection('blog', ({ data }) => !data.draft);
  return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}
const { post } = Astro.props;
const { Content } = await render(post);
---
<article>
  <h1>{post.data.title}</h1>
  <time datetime={post.data.date.toISOString()}>{post.data.date.toLocaleDateString('en-US', { dateStyle: 'medium' })}</time>
  {post.data.hero && <Image src={post.data.hero} alt={post.data.heroAlt} widths={[640, 960, 1200]} sizes="(min-width: 800px) 800px, 100vw" loading="eager" fetchpriority="high" />}
  <Content />
</article>

The collection schema declares hero: image(), so relative image paths in front matter are resolved and type-checked at build time. createPages logic in gatsby-node.js moves into getStaticPaths. Across the site, 34 GraphQL queries became 11 getCollection helpers.

Step 3: Port Components, Decide Hydration

Presentational React components — cards, headers, callouts — copy across unchanged and render to static HTML with no directive. Components that used Gatsby APIs need small edits: <Link> becomes <a>, useStaticQuery becomes a prop passed from an Astro component, and navigate() becomes location.assign. Only interactive components get a client directive, and each directive is a deliberate choice:

ComponentDirectiveWhy
Header, footer, cards, calloutsnonestatic markup
Newsletter formclient:visibleinteractive, below the fold
Pricing toggleclient:idleinteractive, above the fold but not urgent
Code playgroundclient:only="react"browser-only APIs

The costs of each choice are measured in Deferring Hydration with client:visible in Astro.

Where the 238 KB went A stacked bar of Gatsby's 238 kilobytes of JavaScript per page: React and the Gatsby runtime 96 kilobytes, page data and component code 104, and third-party plugins 38. In Astro, static components ship nothing, and the median page ships 14 kilobytes for one newsletter island loaded on visibility. Compressed JavaScript on the median page Gatsby React + runtime 96 page data + components 104 plugins 38 Astro 14 KB · one client:visible island Chrome DevTools coverage, median of five templates, KB brotli
Only one of the site's 41 React components needed to run in the browser on a typical page.

Content From a Headless CMS

About a third of the site's pages came from Contentful through gatsby-source-contentful, not from Markdown. In Astro 5, a content-layer loader pulls those entries at build time into a collection with the same getCollection API as local files, so templates did not need to know where content lived. The loader stores a digest per entry, which means an unchanged Contentful entry is not re-processed on the next build — the main reason warm builds fell to 38 seconds. Rich text fields became HTML through the official rich-text renderer at build time; embedded entries rendered through the same static components as the Markdown pages. The CMS webhook that had triggered Gatsby Cloud builds was pointed at the new host's build hook, with the debounce described in Wiring a Headless CMS to a Static Build. Editors' preview links moved to a draft-enabled preview build, as in Previewing Headless CMS Drafts.

Step 4: Images and URLs

gatsby-plugin-image produced excellent images with blur-up placeholders. Astro's <Picture> generates AVIF and WebP at several widths; the blur placeholder was dropped for the LCP image (it delays the real image) and replaced with a dominant-colour background on others. URLs were kept identical: Gatsby's /blog/post-slug/ maps directly to the route above, and trailingSlash: 'always' matches Gatsby's default. A URL diff in CI between the old sitemap and the new build found 12 mismatches — all pages created programmatically in gatsby-node.js with slightly different slug logic — which were fixed in the route rather than redirected. The technique is in Keeping Redirects Working After an SSG Migration.

Measured Impact

GitHub Actions ubuntu-latest for builds; Lighthouse 12 mobile medians over five templates; field data from RUM over four weeks each side.

MeasureGatsby 5Astro 5
Cold build7 min 50 s1 min 40 s
Warm build (cache restored)3 min 10 s38 s
Compressed JS, median page238 KB14 KB
Lab LCP2.6 s1.2 s
Total Blocking Time410 ms20 ms
Field INP p75240 ms90 ms
Dependencies (npm ls --all)1,640410
Before and after on four measures Paired bars. Cold build fell from 470 seconds to 100. JavaScript per page from 238 kilobytes to 14. Lab LCP from 2.6 seconds to 1.2. Field INP from 240 milliseconds to 90. Gatsby (red) vs Astro (green), each bar scaled to the Gatsby value Cold build 470 s 100 s JS per page 238 KB 14 KB Lab LCP 2.6 s 1.2 s Field INP 240 ms 90 ms
Every measure improved; the JavaScript reduction drove the Core Web Vitals changes and the dependency reduction drove build time.

The migration took eleven engineer-days: two for plugin mapping and scaffolding, four for templates and queries, three for components and images, and two for URL parity, testing and cutover.

Running Both Sites During Cutover

Rather than switching the whole domain at once, the team moved section by section. The CDN routed /blog/* to the new Astro deploy while everything else still came from the Gatsby build, then /docs/* a week later, then the marketing pages. Each switch was a routing rule change that could be reversed in seconds, and each section got a week of field data before the next moved. Two practical details made this work: both builds shared the same header and footer markup (ported first, so readers did not see a visual seam between sections), and both emitted sitemaps that were merged at the edge into one sitemap.xml for the duration. The final cutover — removing the Gatsby origin — happened only after the last section had run clean for two weeks, and the Gatsby project stayed deployable for another month in case something surfaced late.

Pitfalls & Rollback

  • Hydrating everything "to be safe". Wrapping every React component in client:load recreates Gatsby's bundle. Start with no directives.
  • Leaving a Gatsby service worker behind. Returning visitors can keep seeing the old site. Ship a self-destroying worker at the old path for a few months.
  • Porting GraphQL literally. Collections and plain functions are simpler than recreating a query layer; resist building one.
  • Programmatic pages with different slugs. createPages logic often has edge cases; diff URLs in CI.
  • Rollback: keep the Gatsby build deployable on a separate project until the Astro site has four clean weeks; revert DNS or routing to roll back.

Conclusion

Gatsby-to-Astro migrations keep the part that was valuable — React components and Markdown content — and remove the parts that aged badly: the GraphQL layer, the plugin dependence and the full-page hydration. On a 900-page content site that cut the cold build from nearly eight minutes to under two, JavaScript per page by 94%, and field INP from 240 ms to 90 ms, in eleven engineer-days.

FAQ

Can I reuse my Gatsby React components in Astro?

Yes. Astro's React integration renders React components to HTML at build time, and hydrates them in the browser only if you add a client directive. Most presentational components move over unchanged; components that used Gatsby APIs such as useStaticQuery or Link need small edits.

What replaces Gatsby's GraphQL layer?

Astro content collections for Markdown and MDX, and plain imports or fetch calls for other data. Queries become getCollection calls with a filter and sort, which are typed from the collection schema.

What replaces gatsby-plugin-image?

Astro's built-in Image and Picture components, which generate responsive widths and modern formats at build time. Blur-up placeholders need a small addition, but LCP images usually load faster without them.

How much faster is the resulting site?

On our content site, JavaScript per page fell from 238 KB to 14 KB, lab LCP from 2.6 to 1.2 seconds and cold build time from 7 minutes 50 seconds to 1 minute 40 seconds.