Getting Started with Nextjs and GraphCMS
Tags: jamstack, nextjs, react, graphql
Published: 2022-02-04 12:53:41

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643971200620/0YWigu-hZ.jpeg)

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643972587326/EsJWWxLR7.jpeg)




# Let's start Building

## GraphCMS as Headless CMS

### Create a Free Account and Setup the Project

- **Go to the Signup Page** 👉 [Create An Account](https://auth.graphcms.com/login?state=hKFo2SA4Y2oxYV9kMHF4SThfMWpTcHItdDFOdVdGSkdaaS1UbaFupWxvZ2luo3RpZNkgUzh5LW1pOFV6a1RYS3psWVdTS01RTVRoWmtVM1AtZ0ujY2lk2SA4VldTZHlVaHRaVDQzbkFpcHIyZmpLUmhqSm1wOHNZeQ&client=8VWSdyUhtZT43nAipr2fjKRhjJmp8sYy&protocol=oauth2&response_type=id_token&redirect_uri=https%3A%2F%2Fapp.graphcms.com%2Fauth&scope=openid%20https%3A%2F%2Fgraphcms.com%2FloginsCount&initial_screen=signUp&nonce=lUlYL2aSJeemS_OtFYpAkAYD2PMD4wkh&auth0Client=eyJuYW1lIjoiYXV0aDAuanMiLCJ2ZXJzaW9uIjoiOS4xNi4yIn0%3D)




- **Start a New Blank Project**
![Beginner-1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643972874300/ctrJiQSrx.jpeg)

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


- **Choose the Free Plan**

![Beginner-2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973057317/Iv724uLoN.jpeg)

- **Skip this part, You will invite later**

![Beginner-3.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973089939/37o0ag82F.jpeg)

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


- **Here You Go!**

![Beginner-4.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973175383/rRtZMbaD_.jpeg)


- **Creating Content Model (Schema Section)**


![Beginner-5.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973219899/6KogTkAiI.jpeg)

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973352322/CSSO77EMF.jpeg)

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

![Beginner-7.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973359413/r9x1i-9gV.jpeg)


⛳*** 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973507873/Rn7mSrIH0.jpeg)

You will find a list of them.
![Beginner-9.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973519328/qmIpYBJD3.jpeg)

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


**Choosing Fields and Entering Fields Title**


![Beginner-10.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973893833/uJddpiWPE.jpeg)


![Beginner-12.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643974036379/stAxn07dY.jpeg)


![Beginner-11.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643973938167/PPYsj3jDw.jpeg)


![Beginner-13.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643974049763/XEdLBWJnp.jpeg)


- **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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643974404253/037tox6Ow.jpeg)


- Create the Content 


![Beginner-15.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643974407745/Vjz4_JXjH.jpeg)

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

``` 


2. Install  graphql-request


```
yarn add graphql-request

``` 


3. Install GraphQL


```
yarn add graphql

```


- **What we have got**:



![Beginner-20.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976222496/YxErqM_Zz.jpeg)

![Beginner-21.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976214137/ivQrYxPVp.jpeg)


- **We can also add some customer font using Tailwind CSS**:


![Beginner-23.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976296879/QAqgBNhq1.jpeg)



- **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>
  )
}


``` 


- **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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976741307/YBlKroUSy.jpeg)

![Beginner-17.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976752395/IU4iVr9PC.jpeg)


![Beginner-18.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976775943/wROXEcHAp.jpeg)


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

![Beginner-22.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643976965652/gvik3B1jH.jpeg)



![Beginner-23-3.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643977215675/rbAW-62EC.jpeg)


- **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 (
    ...
  )
}

``` 

Done 🎉
We're connected! 


Let's run the app:

``
npm run dev
``

Here is the output:

![Beginner-24-0.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643977379244/-na-mNjVB.jpeg)

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1643977466107/N1jBQI_dOR.jpeg)


![Beginner-19-1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643977559478/1svptZHaIs.jpeg)


This is our query:

```
query {
  greetingMessages {
    greatTitle
    productDescription
  }
}

``` 


**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: {},
  }
}

``` 


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 (
    ...
  )
}

``` 


Let's now see if it really works 😃 after refreshing the server:

![Beginner-24-1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643977981753/MUO64oLV5.jpeg)


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>
  )
}


``` 


Here We Goooo!


![Beginner-24.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643978120551/Rl8k4Lonk.jpeg)




![4488772.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1643978176014/iF8x8yXyM.jpeg)






# 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?](https://codewithkenn.hashnode.dev/did-you-know-you-can-run-a-business-with-headless-cms) 


⚡ [Getting started with GraphCMS](https://medium.com/@ghoshnirmalya/getting-started-with-next-js-and-graphcms-2f3b4cfa2932) 


⚡ [What is Headless CMS](https://www.freecodecamp.org/news/what-is-headless-cms-explained/) 

⚡ [Building a super-fast and secure website with a CMS is no big deal.](https://www.freecodecamp.org/news/building-a-super-fast-and-secure-website-with-a-cms-is-no-big-deal-or-is-it-5ac915c691f2/) 

⚡ [What is Headless CMS](https://www.freecodecamp.org/news/what-is-headless-cms-explained/) 

⚡ [Youtube Videos on Headless CMS](https://www.youtube.com/results?search_query=headless+cms+explained) 

⚡ [Get Started with Gatsby JS and Headless CMS](https://www.youtube.com/watch?v=RaTpreA0v7Q) 





## As Business Owner or Company

⚡ [What is Headless CMS](https://www.freecodecamp.org/news/what-is-headless-cms-explained/) 

⚡ [How To Model And Structure Content For A Headless CMS
](https://www.youtube.com/watch?v=6dNXXQsc_s4) 


⚡ [Should you use WordPress or Headless CMS](https://www.youtube.com/watch?v=rHNl5PZT0VU) 






## Here is my Business Website: 

👉 [WebContract Business for Headless CMS](https://www.webcontract.io)


# 🌎 Let's connect
- [Twitter](https://twitter.com/CodeWithKenn) 
- [Github](https://github.com/KennStack01) 
- [LinkedIn](https://www.linkedin.com/in/kennkibadi/) 
- [Instagram](https://www.instagram.com/codewithkenn_/) 
- [Facebook](https://www.facebook.com/Code-With-Kenn-104376625415201)

- ⚡ [WebContract Business for Headless CMS](https://www.webcontract.io)
- ⚡ [See My Bio Link](https://www.bio.link/IamKenn)


Want to start blogging?  🔥[Join NOW!](https://hashnode.com/@CodeWithKenn/joinme)