DEV Community

Cover image for Blog using Gatsby and Strapi
Sasidharan for Lag and Log

Posted on • Originally published at lagandlog.com on

Blog using Gatsby and Strapi

Gatsby is a React-based framework, popular for performance, static site generation, and scalability. We have covered everything you need to Get Started with Gatsby

Because it is based on React, the website pages are never reloaded which makes the generated website super fast. A large set of plugins is available to allow developers to save time coding.

Strapi is the leading open-source headless CMS. It’s 100% Javascript, fully customizable, and developer-first.

Prerequisites

  • You need to have node v.12 installed.
  • Basic knowledge of ReactJs and Javascript.

Checkout Get Started logs for Gatsby and Strapi,

I am using the same sample application that was created in the above logs. After completing the Gatsby project setup, and start editing the index.js file in /pages folder.

Connect Gatsby with Strapi

Strapi built a plugin for gatsby called gatsby-source-strapi , install the plugin in our Gatsby application using the command,

yarn add gatsby-source-strapi

(or)

npm install gatsby-source-strapi`

Enter fullscreen mode Exit fullscreen mode

This plugin needs to be configured, so inside plugins array add the following code:


{
 resolve: "gatsby-source-strapi",
 options: {
 apiURL: process.env.API_URL || "http://localhost:1337",
 contentTypes: ["blog"],
 queryLimit: 1000,
 },
}

Enter fullscreen mode Exit fullscreen mode

This will allow Gatsby to fetch all our blogs on build time.

Now you can start creating components and layouts for our blog. To get list of all blog posts inside our component refer to the following Graphql query,

import React from "react";
import { graphql, useStaticQuery } from "gatsby";
import PostComponent from "../components/posts";

const IndexPage = () => {
  const data = useStaticQuery(query);

  return (
      <div>
        <div>
          <h1>Posts</h1>
          <PostComponent articles={data.allStrapiPost.edges} />
        </div>
      </div>
  );
};

const query = graphql`
  query {
    allStrapiBlog(filter: { status: { eq: "published" } }) {
      edges {
        node {
          strapiId
          slug
          title
          }
        }
      }
    }
  }
`;

export default IndexPage;

Enter fullscreen mode Exit fullscreen mode

This will query all the posts and the data is passed via data props to the component.

Use the list of posts to render your blog posts on the page. Make your own styles.

Image Source - Strapi Blog

Gatsby blog

You can also use Javascript fetch() to list all posts via a REST API call to localhost:1337/blogs and render it on the screen.

To create pages dynamically for all posts during build time, we have gatsby.node.js file

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(
    `
      {
        posts: allStrapiPost {
          edges {
            node {
              strapiId
              slug
            }
          }
        }
      }
    `
  );

  if (result.errors) {
    throw result.errors;
  }

  // Create blog pages.
  const posts = result.data.articles.edges;

  const PostTemplate = require.resolve("./src/templates/post.js");

  posts.forEach((post, index) => {
    createPage({
      path: `/post/${post.node.slug}`,
      component: PostTemplate,
      context: {
        slug: post.node.slug,
      },
    });
  });
};

Enter fullscreen mode Exit fullscreen mode

It will create pages for all your slugs dynamically.

/post/my-first-post
/post/another-post
/post/my-second-post

Enter fullscreen mode Exit fullscreen mode

using any markdown packages to render your markdown as HTML in Gatsby frontend.

For more details, visit the documentation

Gatsby and Strapi

Happy Coding πŸ‘Ύ

AMA on https://twitter.com/sasiKdharan

Discussion (0)