DEV Community

Cover image for Getting Started with Nextjs and GraphCMS
CodeWithKenn
CodeWithKenn

Posted on

Getting Started with Nextjs and GraphCMS

Hey, there!
This is Kenn, Your Daily Advocate, Business Partner, and Friend from CodeWithKenn!
Welcome to the Blog! Make yourself at home!

ummm-yeah-thanks-for-coming-in-today.jpg

Are you looking for a way to build a website with a faster and easier process? this is for you!
Here I am to help you get started with Headless CMS and React Technologies (Ecosystem).

In a nutshell, today we're going to see how to connect Nextjs as Frontend to GraphCMS as Headless CMS.

The Tech Stack

We're going to use:

  • *Nextjs: **It lets you build server-side rendering and static web applications using React. It's a great tool to build your next website. It has many great features and advantages, which can make Nextjs your first option for building your next web application. *(FreeCodeCamp)

We're going to use it as Frontend.

  • *GraphCMS: **GraphCMS is the Headless CMS allowing you to build digital experiences the way you envisioned them - with all your backends, frontends, and services, working together in harmony. *(GraphCMS)

GraphCMS is going to be used as our Backend.

  • *GraphQL: **GraphQL is a query language and server-side runtime for application programming interfaces (APIs) that prioritizes giving clients exactly the data they request and no more. *(RedHat)

The Communication between Nextjs and GraphCMS is going to be made possible by GraphQL. We'll fetch data using it.

  • **Tailwind CSS: **Tailwind CSS is basically a utility-first CSS framework for rapidly building custom user interfaces.

Hey! In my Blog, I don't complicate stuff. I write simple, useful, and short articles. So 😎 follow me!

download (2).jpg

Let's start Building

GraphCMS as Headless CMS

Create a Free Account and Setup the Project

Enter the Project Name, Description and Select the CDN Node for your Project.

  • Choose the Free Plan

Beginner-2.jpg

  • Skip this part, You will invite later

Beginner-3.jpg

Note: This Section can help you invite your client (if you're doing some Freelance work with somebody).

  • Here You Go!

Beginner-4.jpg

  • Creating Content Model (Schema Section)

Beginner-5.jpg

Give the Content Model Name.
Don't worry, we're gonna explain what a Content model is in a couple of seconds.

Beginner-6.jpg

On our Website, we're gonna Write a Greeting text from GraphCMS and fetch it to the Frontend using GraphQL.

Beginner-7.jpg

β›³*** A content model documents all the different kinds of content you have on your website. It breaks content types down into their component parts, describes them in detail, and maps out how they relate to one another.***

  • Content Model Details Structure

In this step, you only have to choose what you really want to use. You can find many data fields you can explore, such as Single Text, Multi-Line Text, Markdown, Slug, Image, Rich-Text, Date, Localization.

Note: Most of the Headless CMSs have the same data types in their platforms. So, One you mastered this, You can use whatever Headless CMS you want.

Beginner-8.jpg

You will find a list of them.
Beginner-9.jpg

We're gonna use the Single-line text and Multi-line text fields.

Choosing Fields and Entering Fields Title

Beginner-10.jpg

Beginner-12.jpg

Beginner-11.jpg

Beginner-13.jpg

  • Let's Enter our Welcome Text (Content Section)

  • Go to the Next Section (Content) and Choose the Schema (GrettingMessage for our Project)

Beginner-14.jpg

  • Create the Content

Beginner-15.jpg

Note: This can be created as many as we want. For Example, we can create many employees' names to show on the Website.

Nextjs as our Frontend Framework

  • We'll be using a Nextjs + Tailwind CSS Starter and Install GraphQL:
  1. Install The Project
npx create-next-app --example with-tailwindcss with-tailwindcss-app
# or
yarn create next-app --example with-tailwindcss with-tailwindcss-app

Enter fullscreen mode Exit fullscreen mode
  1. Install graphql-request
yarn add graphql-request

Enter fullscreen mode Exit fullscreen mode
  1. Install GraphQL
yarn add graphql

Enter fullscreen mode Exit fullscreen mode
  • What we have got:

Beginner-20.jpg

Beginner-21.jpg

  • We can also add some customer font using Tailwind CSS:

Beginner-23.jpg

  • Let's clean the Index Component Page:
import Head from 'next/head'

export default function Home() {


  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <Head>
        <title>Next - Headless CMS</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className="flex w-full flex-1 flex-col items-center justify-center px-20 text-center">
        <h1 className="text-6xl font-bold">
          Welcome to{' '}
          <a className="text-blue-600" href="https://graphcms.com">
            GraphCMS
          </a>
        </h1>



        <div className="mt-6 flex max-w-4xl flex-wrap items-center justify-around sm:w-full"></div>
      </main>

      <footer className="flex h-24 w-full items-center justify-center border-t">
        <a
          className="flex items-center justify-center"
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <img src="/vercel.svg" alt="Vercel Logo" className="ml-2 h-4" />
        </a>
      </footer>
    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode
  • Let's Connect Nextjs to GraphCMS:

Go back to the CMS in the Project Settings Page, then to the Public Content API, and Copy the Content API Key.

Beginner-16.jpg

Beginner-17.jpg

Beginner-18.jpg

After that, Let's Go back in Nextjs and Create a .env.local and paste the API key as below:

Beginner-22.jpg

Beginner-23-3.jpg

  • Let's Import graphql-request into our index.js project:
import { GraphQLClient } from 'graphql-request'

// And let's initialize our GraphQL Client project

const graphcms = new GraphQLClient(process.env.GRAPHQL_URL_ENDPOINT)


export default function Home() {

  return (
    ...
  )
}

Enter fullscreen mode Exit fullscreen mode

Done πŸŽ‰
We're connected!

Let's run the app:


npm run dev

Here is the output:

Beginner-24-0.jpg

Note: This doesn't come from the CMS, remember we made it from the index.js file. πŸ€”

Now, Let's create our query from GraphCMS

Beginner-19.jpg

Beginner-19-1.jpg

This is our query:

query {
  greetingMessages {
    greatTitle
    productDescription
  }
}

Enter fullscreen mode Exit fullscreen mode

Let's add it into Nextjs Γ¬ndex.js file using the getStaticProps function:

// Query Data
export async function getStaticProps() {
  try {
    const query = `
      query {
        greetingMessages {
          greatTitle
          productDescription
        }
      }
    `

    const { greetingMessages } = await graphcms.request(query)

    return {
      props: {
        greetingMessages,
      },
    }
  } catch (error) {
    console.log(error)
  }

  return {
    props: {},
  }
}

Enter fullscreen mode Exit fullscreen mode

Note: We have used the try...catch method for simple error handling, but it's not a big deal πŸ‘‹

Last Step: Import The GreetingMessages as a Prop into the main Component:

export default function Home({ greetingMessages }) {

  return (
    ...
  )
}

Enter fullscreen mode Exit fullscreen mode

Let's now see if it really works πŸ˜ƒ after refreshing the server:

Beginner-24-1.jpg

Yes, it does work! πŸ”₯

Let's render the data and view it on the front page πŸ˜ƒ

export default function Home({ greetingMessages }) {

  return (
   <div>
        ...
     <div className="mx-auto flex flex-col">
          {greetingMessages?.map((content, index) => (
            <div key={index} className="my-10">
              <h1 className="text-xl font-bold"> {content.greatTitle} </h1>
              <p className="text-md my-5 text-justify font-medium">
                {' '}
                {content.productDescription}{' '}
              </p>
            </div>
          ))}
        </div>
        ...
</div>
  )
}


Enter fullscreen mode Exit fullscreen mode

Here We Goooo!

Beginner-24.jpg

4488772.jpg

Alright! Thanks for Reading!

Stay tuned! More articles are coming out! Feel free to follow, comment, and share the articles to support me πŸ€™

Useful Resources for the Journey

To go further in your journey, here are the resources you need:

As a Developer

⚑ Did you know you can run a Business with Headless CMS?

⚑ Getting started with GraphCMS

⚑ What is Headless CMS

⚑ Building a super-fast and secure website with a CMS is no big deal.

⚑ What is Headless CMS

⚑ Youtube Videos on Headless CMS

⚑ Get Started with Gatsby JS and Headless CMS

As Business Owner or Company

⚑ What is Headless CMS

⚑ How To Model And Structure Content For A Headless CMS

⚑ Should you use WordPress or Headless CMS

Here is my Business Website:

πŸ‘‰ WebContract Business for Headless CMS

🌎 Let's connect

Want to start blogging? πŸ”₯Join NOW!

Top comments (0)