🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Astro Fundamentals••By Komal Nakrani

Gatsby to Astro Migration: A Practical Step-by-Step Guide

Migrate from Gatsby to Astro: replace GraphQL with content collections, port React components, swap gatsby-plugin-image, rebuild createPages routes and keep URLs.

#Astro#Gatsby#Migration#React#Gatsby to Astro

To migrate from Gatsby to Astro, create an Astro project with the React integration, copy your components into src/components/, replace Gatsby’s GraphQL queries with content collections or direct fetch calls in page frontmatter, and turn createPages templates into dynamic routes with getStaticPaths(). Then swap gatsby-plugin-image for <Image /> from astro:assets, Gatsby’s Link for plain <a> tags, and the Head API for an Astro layout, keeping every URL the same.

Gatsby to Astro is one of the most common migrations because the sites are similar: static, content-heavy and built with React. Gatsby’s development has slowed considerably since 2023, and many teams want fewer plugins, faster builds and less JavaScript on each page.

Key Takeaways

  • React components move over almost unchanged. Gatsby-specific imports (gatsby, gatsby-plugin-image) need replacing.
  • Astro has no GraphQL layer. Content collections and plain await in frontmatter replace page and static queries.
  • gatsby-node.js createPages logic becomes getStaticPaths() in a dynamic route file.
  • Most Gatsby plugins have an Astro equivalent that is either built in or an official integration.
  • Gatsby sites hydrate React on every page; Astro hydrates only components you mark, so pages usually ship far less JavaScript.

Concept map: Gatsby to Astro

Gatsby Astro
src/pages/about.js src/pages/about.astro
Template + createPages in gatsby-node.js src/pages/blog/[slug].astro with getStaticPaths()
Page query (export const query = graphql) getCollection() or fetch in frontmatter
useStaticQuery Import data or query in the parent .astro file and pass props
gatsby-source-filesystem + gatsby-transformer-remark Content collection with glob() loader
gatsby-plugin-mdx @astrojs/mdx
gatsby-plugin-image <Image /> / <Picture /> from astro:assets
Link from gatsby <a href> plus prefetch
Head API / react-helmet <head> in a layout component
gatsby-plugin-sitemap @astrojs/sitemap
gatsby-plugin-feed @astrojs/rss
gatsby-browser.js wrappers Providers inside each island
static/ public/
Gatsby Functions Endpoints in src/pages/api/ with an adapter

Step 1: Set up the Astro project

npm create astro@latest my-site-astro
cd my-site-astro
npx astro add react mdx sitemap

Copy static/ into public/. If you used Tailwind CSS, run npx astro add tailwind. If you used CSS Modules or Sass, they work in Astro too; Sass needs the sass package. The folder structure docs show the layout of an Astro project.

Step 2: Move content into collections

Most Gatsby blogs source Markdown from a folder with gatsby-source-filesystem and query it through GraphQL. In Astro, define a collection:

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
  schema: ({ image }) =>
    z.object({
      title: z.string(),
      date: z.coerce.date(),
      description: z.string().optional(),
      featuredImage: image().optional(),
    }),
});

export const collections = { blog };

Move content/blog/** into src/content/blog/. Gatsby blogs often use one folder per post with index.md and images beside it; that structure works with the glob() loader, and relative image paths in frontmatter are resolved by the image() helper. Each entry’s id is derived from its path, so a post at my-post/index.md gets the id my-post. The content collections guide covers the details.

Step 3: Replace GraphQL page queries

A Gatsby blog index:

// src/pages/blog.js (Gatsby)
import { graphql, Link } from 'gatsby';

export default function Blog({ data }) {
  return (
    <ul>
      {data.allMarkdownRemark.nodes.map((post) => (
        <li key={post.fields.slug}>
          <Link to={post.fields.slug}>{post.frontmatter.title}</Link>
        </li>
      ))}
    </ul>
  );
}

export const query = graphql`
  query {
    allMarkdownRemark(sort: { frontmatter: { date: DESC } }) {
      nodes { fields { slug } frontmatter { title } }
    }
  }
`;

becomes:

---
// src/pages/blog/index.astro
import { getCollection } from 'astro:content';
import Layout from '../../layouts/Layout.astro';

const posts = (await getCollection('blog')).sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---
<Layout title="Blog">
  <ul>
    {posts.map((post) => (
      <li><a href={`/blog/${post.id}/`}>{post.data.title}</a></li>
    ))}
  </ul>
</Layout>

No schema to learn, no query language, and the result is fully typed from your collection schema.

Step 4: Turn createPages into a dynamic route

Gatsby generates post pages in gatsby-node.js:

// gatsby-node.js (Gatsby)
exports.createPages = async ({ graphql, actions }) => {
  const result = await graphql(`{ allMarkdownRemark { nodes { id fields { slug } } } }`);
  result.data.allMarkdownRemark.nodes.forEach((node) => {
    actions.createPage({
      path: node.fields.slug,
      component: require.resolve('./src/templates/post.js'),
      context: { id: node.id },
    });
  });
};

In Astro, the template and the page list live in one file:

---
// src/pages/blog/[...slug].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
import Layout from '../../layouts/Layout.astro';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---
<Layout title={post.data.title} description={post.data.description}>
  <article>
    <h1>{post.data.title}</h1>
    {post.data.featuredImage && <Image src={post.data.featuredImage} alt="" width={1200} priority />}
    <Content />
  </article>
</Layout>

Using a rest parameter ([...slug]) lets slugs contain slashes, which matches Gatsby sites that used nested paths. If your Gatsby slugs were generated differently (for example with dates), reproduce that logic when building params.

Step 5: Port components

Copy src/components/ across. Replace Gatsby-specific imports:

  • import { Link } from 'gatsby' becomes a plain <a>. Add prefetch: true to astro.config.mjs for prefetching similar to Gatsby’s.
  • StaticImage and GatsbyImage become <Image /> in .astro files. Inside React components, accept an image URL and dimensions as props, generated by the parent with getImage() or <Image />.
  • useStaticQuery disappears. Query in the .astro parent and pass data down as props.
  • Wrappers in gatsby-browser.js (theme providers, query clients) need to wrap each island that uses them.

Components without interactivity become static HTML automatically. Add a directive only to interactive ones:

---
// src/pages/index.astro
import Layout from '../layouts/Layout.astro';
import Hero from '../components/Hero.jsx';
import Newsletter from '../components/Newsletter.jsx';
---
<Layout title="Home">
  <Hero />                       <!-- static HTML -->
  <Newsletter client:visible />  <!-- hydrates when scrolled into view -->
</Layout>

The client directive guide explains each option.

Step 6: Head tags, sitemap and RSS

Replace the Head API or react-helmet with a layout that sets <title>, description, canonical and Open Graph tags from props. Set site in astro.config.mjs so canonical and sitemap URLs are absolute. Then add a feed:

// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import type { APIContext } from 'astro';

export async function GET(context: APIContext) {
  const posts = await getCollection('blog');
  return rss({
    title: 'My Blog',
    description: 'Notes and tutorials',
    site: context.site!,
    items: posts.map((p) => ({ title: p.data.title, pubDate: p.data.date, link: `/blog/${p.id}/` })),
  });
}

Use the same feed path Gatsby used (often /rss.xml) so subscribers keep receiving posts. The Astro sitemap tip covers sitemap options.

Step 7: Plugins without a direct equivalent

Gatsby plugin Astro approach
gatsby-plugin-manifest Static manifest.webmanifest in public/
gatsby-plugin-offline A service worker library such as Workbox, if you still need it
gatsby-plugin-google-gtag Script tag in the layout, or Partytown via @astrojs/partytown
gatsby-remark-prismjs Built-in Shiki syntax highlighting
gatsby-remark-images Automatic for relative images in Markdown
gatsby-source-contentful and other CMS sources A content loader or fetch in frontmatter

The headless CMS guide covers loaders for common CMSs.

Step 8: Verify and launch

  1. Export the list of URLs from Gatsby’s sitemap.
  2. Build the Astro site and check each URL returns 200 in dist/, or add a redirect.
  3. Check that trailing slash behaviour matches (Gatsby defaults to trailing slashes); set trailingSlash: 'always' if needed.
  4. Compare page titles, descriptions and canonical tags on key pages.
  5. Run Lighthouse on the same pages before and after.

The official Gatsby migration guide lists further mappings.

If the design is due for a refresh anyway, moving your Markdown into a finished Astro theme can be quicker than porting old components; the Komal blog and editorial themes are complete Astro 7 projects built around content collections.

FAQ

Is it hard to migrate from Gatsby to Astro?

For most blogs and marketing sites, no. Markdown and React components move over with small changes. The main work is replacing GraphQL queries and Gatsby plugins, which usually simplifies the codebase.

Can I keep my React components when moving from Gatsby to Astro?

Yes. Add React with npx astro add react. Components render to HTML by default and hydrate only when you add a client:* directive.

Does Astro have something like Gatsby’s GraphQL data layer?

No. Astro uses content collections with typed schemas and loaders, plus plain fetch in frontmatter. Most teams find this simpler than GraphQL for content sites.

What replaces gatsby-plugin-image in Astro?

The <Image /> and <Picture /> components from astro:assets, which resize images, generate srcset and output modern formats at build time.

Will my Gatsby URLs change when I move to Astro?

Only if you let them. Build the same paths in getStaticPaths(), match trailing slash settings, and add redirects for anything you rename.