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 (frompublic/sitemap-*.xmlor 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 plugin | Astro equivalent |
|---|---|
gatsby-source-filesystem + gatsby-transformer-remark / gatsby-plugin-mdx | content collections + @astrojs/mdx |
gatsby-plugin-image / gatsby-image | astro: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, -offline | a static manifest; drop the service worker unless needed |
gatsby-remark-prismjs | built-in Shiki highlighting |
gatsby-plugin-google-gtag | a deferred first-party script or Partytown |
gatsby-source-contentful | a 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.
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:
| Component | Directive | Why |
|---|---|---|
| Header, footer, cards, callouts | none | static markup |
| Newsletter form | client:visible | interactive, below the fold |
| Pricing toggle | client:idle | interactive, above the fold but not urgent |
| Code playground | client:only="react" | browser-only APIs |
The costs of each choice are measured in Deferring Hydration with client:visible in Astro.
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.
| Measure | Gatsby 5 | Astro 5 |
|---|---|---|
| Cold build | 7 min 50 s | 1 min 40 s |
| Warm build (cache restored) | 3 min 10 s | 38 s |
| Compressed JS, median page | 238 KB | 14 KB |
| Lab LCP | 2.6 s | 1.2 s |
| Total Blocking Time | 410 ms | 20 ms |
| Field INP p75 | 240 ms | 90 ms |
Dependencies (npm ls --all) | 1,640 | 410 |
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:loadrecreates 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.
createPageslogic 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.
Related
- Parent: Migrating Between Static Site Generators — the migration playbook.
- Migrating from Gatsby to Next.js Static Export — the other common destination.
- Astro Islands vs Full Hydration Performance — why the JavaScript bill fell.
- Converting Front Matter at Scale During Migration — the content conversion step.
- Image Optimization Pipelines in Astro — replacing gatsby-plugin-image.