DEV Community

Cover image for How to add a CMS to your Gatsby Website
Helitha Rupasinghe
Helitha Rupasinghe

Posted on • Updated on

How to add a CMS to your Gatsby Website

What is GatsbyJS?

Gatsby is a framework for creating blazing fast websites and web applications. Powered by React and GraphQL, Gatsby gives you everything you need to build and launch your next project.

Go to this page here

Why Choose Contentful CMS?

Contentful is a headless content management system (CMS). You upload your content (be it text, images, or video) to Contentful, and from there can organize and edit it as you desire.

Get all the Details here

Prerequisities

This post will assume that you have a Gatsby project already set up. If you need to set up a project, head to this page, then come back.

Gatsby Integration With Contentful

npm install gatsby-source-contentful
Enter fullscreen mode Exit fullscreen mode

How to use it?

Create the gatsby config file and add the following code

plugins: [
  {
    resolve: `gatsby-source-contentful`,
    options: {
      spaceId: `your_space_id_grab_it_from_contentful`,
      accessToken: `your_token_id_grab_it_from_contentful`,
    },
  },
]
Enter fullscreen mode Exit fullscreen mode

Connect your gatsby website and contentful CMS.

Here is an example of what a GraphQL query looks like...

import React from 'react'
import Layout from '../components/Layout'
import { graphql, Link, useStaticQuery } from 'gatsby'
import * as styles from './blog.module.scss'
import Meta from '../components/head'

const BlogPage = () => {
    const { allContentfulBlogPost: { edges } } = useStaticQuery(graphql`
        query {
            allContentfulBlogPost (
                sort: {
                    fields: publishedDate
                    order: DESC
                }
            ) {
                edges {
                    node {
                        title
                        slug
                        # publishedDate(fromNow: true)
                        # format uses momentjs
                        publishedDate(formatString: "MMMM Do, YYYY")
                    }
                }
            }
        }
    `)
    return (
        <Layout>
            <Meta title="Blogs" />
            <h1>Blog</h1>
            <ol className={styles.posts}>
                {edges.map((edge, index) =>(
                    <li key={index} className={styles.post}>
                        <Link to={`/blog/${edge.node.slug}`}>
                            <h2>{edge.node.title}</h2>
                            <p>{edge.node.publishedDate}</p>
                        </Link>
                    </li>
                ))}
            </ol>
        </Layout>
    )
}

export default BlogPage
Enter fullscreen mode Exit fullscreen mode

Talk Later!

Top comments (0)