Next.js Quick start guide

Estimated duration: 10 minutes

This guide shows you how to connect Prepr to a Next.js project to get data from Prepr CMS. You'll learn how to make a simple blog with Next.js and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.

blog site end result

If you want to skip ahead, try out the zero installation demo on Stackblitz (opens in a new tab) or clone the repository on GitHub (opens in a new tab) to run the demo locally. These resources and the steps below are based on the latest version of Next.js including the App router.


You can also watch the video for step-by-step instructions that are detailed in the guide below.



This video was created using AI avatars and voices to ensure a consistent look and feel. The use of AI matches our culture of using innovative technologies.

Prerequisites

You need to have the following setup before you connect your Next.js project to Prepr.

Step 1: Create a new Next.js project

The instructions below will guide you on how to create an empty Next project for your blog app.

Install Next.js

You can skip this step if you have an existing Next project.

  1. Open a terminal and execute the following command to create a new Next project called prepr-next:
npx create-next-app@latest prepr-next && npm i next@latest

Mark the options as shown in the image below to create the same project structure used in this guide.

default options

  1. Now that the project is successfully created, go to the prepr-next folder, the root directory of the project, and run the project with the following commands in the terminal:
cd prepr-next
npm run dev
  1. You should now be able to view your app on your localhost, for example, http://localhost:3000/ (opens in a new tab).

  2. Open your project with your preferred code editor.

  3. Go to the app folder and replace the code in the page.js file with the following code to display your blog:

./app/page.js
export default async function Home() {
  return (
    <div>
      <h1>My blog site</h1>
    </div>
  );
}
  1. Go to the layout.js file in the app folder and replace the default code with the simplified layout below.
./app/layout.js
export const metadata = {
  title: 'My blog site',
  description: 'A simple blog app project',
}
 
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
  1. Empty the globals.css file in the app folder to remove the existing formatting.

Next.js version 13 introduced new file conventions to create shared layouts. For more details, check out the Next.js docs (opens in a new tab).

You should now see something like the image below on your localhost.

view component

Step 2: Install the Apollo client

The Apollo client is an integration tool that helps to retrieve CMS data with GraphQL. The instructions below show you how to install the Apollo client so that you can add GraphQL queries to request data from the Prepr API.

  1. Stop the server you started in the above step (CTRL-C) and execute the following command in the terminal:
npm install @apollo/client graphql
  1. Create a services folder in the root directory of the project. Then, create a file called apollo-client.js in this folder. Copy the following code to this file to import and initialize the Apollo client:
./services/apollo-client.js
import { ApolloClient, InMemoryCache } from "@apollo/client";
 
const client = new ApolloClient({
    uri: `https://graphql.prepr.io/${process.env.PREPR_ACCESS_TOKEN}`,
    cache: new InMemoryCache(),
});
 
export default client;

This client will be used to make API requests to endpoints provided by the Prepr CMS across your Next application.

  1. We recommend using environment variables to store sensitive information like access tokens. To add environment variables, create a .env file in the root directory of your project and add the access token like this:
./.env
PREPR_ACCESS_TOKEN=<YOUR-ACCESS-TOKEN>
  1. Replace the placeholder value <YOUR-ACCESS-TOKEN> with an access token from Prepr. Get an access token by logging into your Prepr account:
    a. Go to Settings → Access tokens to view all the access tokens.
    b. Copy the GraphQL Production access token to only retrieve published content items on your site.

access token

Use the GraphQL Production access token to request published content items for your live app and use the GraphQL Preview token to make a preview of unpublished content items for your content editors.

  1. Execute the following command to restart the server and to make sure that the Apollo client is installed correctly:
npm run dev

If your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the installed Apollo client.

Step 3: Fetch multiple articles

Now that your Apollo client is installed and connected to Prepr, fetch the blog articles from Prepr.

Add a GraphQL query

  1. Create a queries folder in the root directory of your project and create a file named get-articles.js.

  2. Add the following query to this file to retrieve all articles:

./queries/get-articles.js
import { gql } from "@apollo/client";
 
export const GetArticles = gql`
  query {
    Articles {
    items {
      _id
      _slug
      title
    }
  }
 }
`

You can create and test GraphQL queries using the Apollo explorer (opens in a new tab) from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.

If you’re using preloaded demo data in your Prepr CMS environment as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.

demo articles

In the next step, we'll fetch and process the query response.

Fetch data

Now that the query has been added, fetch the articles from Prepr and display them in the app.

  1. Open the page.js file in the app folder and replace the content with the code below to display the data retrieved from the query.

For different rendering and caching options, check out the Next.js docs (opens in a new tab) for more details.

./app/page.js
import client from '@/services/apollo-client';
import { GetArticles } from '@/queries/get-articles';
 
export const revalidate = 0;
 
async function getData() {
 
  // Make the query request
  const {data} = await client.query({
    query: GetArticles,
  });
 
  // Return the list of articles from the query results
  return data.Articles.items;
}
 
export default async function Home() {
  const articles = await getData();
  
  /* Optional: Print query output to the terminal */
  console.log(JSON.stringify(articles, undefined, 2));
 
  return (
    <div>
      <h1>My blog site</h1>
      <ul>
        {articles.map((article) => (
 
          // Display a list of the fetched articles
          <li key={article._id}>
            {article.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

Now when you view the website on your localhost, you'll see something like the image below.

Local

Step 4: Fetch individual articles

Now that you have the list of articles, add links to them. When a visitor clicks on a link, your app should open a detailed article page automatically. The instructions below show you how to set up the routing from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.

Add links

First add links to the articles.

  1. Update the page.js file to include a link tag on each article title as shown in the code below.
./app/page.js
import { GetArticles } from '@/queries/get-articles';
import client from '@/services/apollo-client';
 
/* Import Next links to add links to the article titles */
import Link from "next/link";
 
export const revalidate = 0;
 
async function getData() {
  const {data} = await client.query({
    query: GetArticles,
  });
  return data.Articles.items;
}
 
export default async function Home() {
  const articles = await getData();
 
  return (
    <div>
      <h1>My blog site</h1>
      <ul>
        {articles.map((article) => (
          <li key={article._id}>
 
            {/* Add links to the article title and use the article slug to open the new page */}
            <Link href={article._slug}>{article.title}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

Now when you view the app, each article has its own link. When you click on the link, a new page opens with the slug in the URL, but a Page 404 error is displayed. Continue with the next step to fetch the article details and resolve this error.

Fetch article details

Add another query to fetch a specific article by its slug and make this page visible when clicking on an article.

  1. Create a file called get-article-by-slug.js in the queries folder and add the following to query a specific article by its slug:
./queries/get-article-by-slug.js
import { gql } from "@apollo/client";
 
export const GetArticleBySlug = gql`
query ($slug: String) {
   Article (slug: $slug) {
     _id
     title
     content {
       __typename
       ... on Text {
        _id
        body
        text
       }
       ... on Assets {
         items {
          _id
          url
         }
       }
     }
   }
}`

Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.

The Article content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.

  1. Open the app folder and create a new folder called [slug]. Create a new page.js in this folder and add the code below to fetch an article by its slug and display the article details.
./app/[slug]/page.js
import client from '@/services/apollo-client';
 
// Import the query
import {GetArticleBySlug} from '@/queries/get-article-by-slug';
 
export const revalidate = 0;
 
async function getData(slug) {
 
  // Make a query request for an article by its slug 
  const {data} = await client.query({
    query: GetArticleBySlug,
    variables: {
      slug
    }
  })
 
  // Return the article from the query results
  return data.Article
}
 
export default async function ArticlePage({params}) {
 
  // Get the slug from the URL params
  const {slug} = params;
  const article = await getData(slug);
 
  return (
    <>
      <h1>
        { article.title }
      </h1>
 
      {/* Loop through content types in article content */}
 
      {article.content.map((contentType) => {
 
         // Check if an image exists in the array and if so, display it.
        if (contentType.__typename === 'Assets' && contentType.items.length) {
          return (
            <div className="my-10" key={contentType.items[0]?._id}>
              <img
                src={contentType.items[0]?.url}
                width="300"
                height="250"
              />
            </div>
          )
        }
 
        // Display text as HTML
        if (contentType.__typename === 'Text') {
 
          return (
            <div key={contentType._id} dangerouslySetInnerHTML={{ __html: contentType.body }}></div>
          )
        }
      })}
    </>
  )
}

Now, when you view your site, you can click on an article which will direct you to that specific article like in the image below.

article detail

All done

Congratulations! You have successfully connected a Next project to Prepr for a simple Blog app.

Next steps

To learn more on how to expand your project, check out the following resources:

Was this article helpful?

We’d love to learn from your feedback