DEV Community

webspeller
webspeller

Posted on

Getting Started with Strapi and Gatsby

A headless CMS offers content delivery via APIs, giving you the flexibility to use content on any platform or technology you need. This approach is popular among web and mobile developers for building efficient, scalable applications.

This guide will walk you through integrating Strapi as the backend CMS and Gatsby for the front end, covering data querying and page generation. First, let’s dive into what Strapi is.

What is Strapi?

Strapi is an open-source headless CMS designed for easy content management and customization. Here are some of its key benefits:

  • Full Data Control: Strapi lets you host and manage your own data storage, offering complete control.
  • Self-hosted Flexibility: Host and scale Strapi projects on any platform you prefer—AWS, Render, Netlify, Heroku, or a dedicated server.
  • Database Agnostic: Strapi supports SQL and NoSQL databases, including MongoDB, PostgreSQL, MySQL, MariaDB, and SQLite.
  • Customizable APIs: Strapi enables you to customize APIs, routes, and plugins, tailoring the CMS to your specific project needs.

Additionally, Strapi supports GraphQL, which you can enable via plugins for smooth data retrieval.

Why Use Strapi with Gatsby?

Gatsby is a static site generator that offers performance, security, cost-effective scaling, and a great developer experience. Paired with Strapi, Gatsby gains flexibility in handling dynamic content, making it an ideal choice for static sites or dynamic apps. As a data source, Strapi provides the flexibility Gatsby needs to generate static pages from structured content types.

Now, let’s build a blog using Strapi and Gatsby!

Step 1: Install Strapi and Create a Project

To get started, create a Strapi project using the following command:

yarn create strapi-app my-project --quickstart
Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, go to http://localhost:1337/admin to set up an administrator account and create content types like “Post,” “Category,” and “Author.”

Step 2: Set Up a Gatsby Site

Create a basic Gatsby site using the Gatsby CLI:

gatsby new gatsby-app
Enter fullscreen mode Exit fullscreen mode

Then, configure Gatsby to interact with Strapi by installing the gatsby-source-strapi plugin:

yarn add gatsby-source-strapi
Enter fullscreen mode Exit fullscreen mode

In your Gatsby configuration file (gatsby-config.js), add the plugin:

{
  resolve: "gatsby-source-strapi",
  options: {
    apiURL: "http://localhost:1337",
    contentTypes: ["post", "category", "author"],
    queryLimit: 1000,
  },
}
Enter fullscreen mode Exit fullscreen mode

Ensure you’ve enabled the find and findOne permissions for each content type in Strapi’s settings.

Step 3: Fetch and Display Data in Gatsby

With the plugin configured, you can start querying data from Strapi. Here’s a sample GraphQL query to fetch posts:

query {
  allStrapiPost {
    edges {
      node {
        id
        title
        content
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Generate Pages in Gatsby

To dynamically generate pages for posts, categories, and authors, add the following code to your gatsby-node.js file:

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions;

  return graphql(`
    {
      allStrapiPost {
        edges {
          node {
            id
            title
          }
        }
      }
    }
  `).then(({ data }) => {
    data.allStrapiPost.edges.forEach(({ node }) => {
      createPage({
        path: `/posts/${node.title}`,
        component: path.resolve(`./src/templates/post.js`),
        context: { id: node.id },
      });
    });
  });
};
Enter fullscreen mode Exit fullscreen mode

Repeat this process for categories and authors by changing the query and file path.

Step 5: Build Template Components

For each content type, create a corresponding template file in src/templates. Here’s an example for a Post template:

import React from 'react';
import { graphql } from 'gatsby';

export const query = graphql`
  query Post($title: String!) {
    posts: strapiPost(title: { eq: $title }) {
      title
      content
      category { name }
      author { name }
    }
  }
`;

const Post = ({ data }) => {
  const { title, content, category, author } = data.posts;
  return (
    <div>
      <h1>{title}</h1>
      <p>{content}</p>
      <p>Category: {category.name}</p>
      <p>Author: {author.name}</p>
    </div>
  );
};

export default Post;
Enter fullscreen mode Exit fullscreen mode

You can do the same for category.js and author.js templates.

Viewing Your Pages

To view your new pages, navigate to URLs like http://localhost:8000/posts/title-of-post or http://localhost:8000/categories/category-name.

And that’s it! You’ve now successfully integrated Strapi with Gatsby to build a flexible, scalable blog. Feel free to explore and customize further to meet your project’s needs.

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay