Building a Next.js Blog with Contentful Integration

by Ebimene Agent , Software Engineer

Prerequisites

Ensure that you have Node.js installed on your local machine and you have some knowledge of nextjs.

Create a Content Model in Contentful

  1. Login to Contentful:Access your Contentful account.
  2. Create a New Space: If you haven't already, create a new space for your blog.
  3. Define a Content Model:
  • Navigate to the "Content Model" section.
  • Click "Create Content Type" and name it "BlogPost".
  • Add fields like "Title" (Text), "Content" (Rich Text), "Date" (Date & Time),slug(this will be generated from automatically from the title) and any other fields you need.
  1. Create Sample Entries:
  • Go to the "Content" section.
  • Add a few sample blog entries.

Setting Up a Next.js Project

  • Creating a new Next.js app using create-next-app
   npx create-next-app my-nextjs-contentful-app
   cd my-nextjs-contentful-app
   npm run dev

Install Contentful SDK

If you haven't installed the Contentful SDK in your Next.js project, run the following command:

npm install contentful

Environment Variables

For you to successfully fetch the blogs from your contenful space, you need to have two environment variables that you can generate from your contentful space: CONTENTFUL_SPACE_ID and CONTENTFUL_ACCESS_TOKEN. To get these environment variables, go to the settings of your space and click on API Keys. Then, click on Add API Key. Give it any name of your choice. You can add a description or leave it. Then copy the space id and access token values and add them to the two environment variables mentioned above in your .env file(Create this from the root folder).

Fetch Content from Contentful

Create a folder in your app or__ src's__ folder called utils and create a file in it and name it contentful.js to fetch blog posts and any other contents you may want to fetch from contenful:

import { createClient } from 'contentful';

export const createContentClient = () => {
  return createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
  })
}
const client = createContentClient()

export const getEntriesByType = async (type) => {
  const response = await client.getEntries({
    content_type: type,
  })

  return response.items
}

  export const getBlogPosts = async () => {
  const results = await getEntriesByType('blogPost')
  const blogPosts = results.map((blog) => blog.fields)
  return blogPosts
}

export const getEntryBySlug = async (slug, type) => {
  const queryOptions = {
    content_type: type,
    'fields.slug[match]': slug,
  }
  const queryResult = await client.getEntries(queryOptions)
  return queryResult.items[0]
}

Displaying Content from Contentful

In the component that you want to display it, you can import the getBlogPosts function and call it to get our blogs in contentful. In our case, we want to display the blogs in the page.js file in the app's folder. Update the file with the following code:

import Link from "next/link";
import { getBlogPosts } from "./utils/contentful";

async function Home() {
const blogs= await getBlogPosts();
return (
  <div>
    <h1>Latest Blog Posts</h1>
   {blogs.map((blog) => (
        <div key={blog.slug}>
          <Link href={`${blog.slug}`}> {blog.title}</Link>
        </div>
      ))}
  </div>
);
}

export default Home;

Dynamic Routing

Implement dynamic routing for individual blog posts: Create a folder inside the app's folder with parenthesis and name it [slug] and create a page.js file inside it. Update the file with the code below:

import { getEntryBySlug, createContentClient } from "../utils/contentful";

const client = createContentClient();
export async function generateStaticParams() {
  const queryOptions = {
    content_type: "blogPost",
    select: "fields.slug",
  };
  const articles = await client.getEntries(queryOptions);
  return articles.items.map((article) => ({
    slug: article.fields.slug,
  }));
}

export default async function BlogPage(props) {
  const { params } = props;
  const { slug } = params;
  const blog = await getEntryBySlug(slug, "blogPost");
  const { title, content } = blog.fields;

  return (
    <div>
      <h1>Welcome to the blog post</h1>
      <h3>{title}</h3>
      <p>{content}</p>
    </div>
  );
}

Conclusion

By following this comprehensive guide, you have successfully integrated Contentful with Next.js, empowering you to build dynamic and content-driven web applications. This powerful combination provides flexibility, scalability, and an excellent developer experience.

Feel free to explore further features and optimizations( like stylings and others) to tailor your application to specific requirements. Happy coding!

Schedule a demo

More articles

Subscription-Based Dental Plans: A Marketing Angle Patients Love

The traditional dental insurance model is broken. With rising premiums, limited coverage, and frustrating claim denials, both patients and practices are seeking alternatives. Enter subscription-based dental plans – a game-changing marketing approach that transforms patient relationships while boosting practice revenue

Read more

How Short-Form Video Is Shaping the Future of Cosmetic Dentistry

Short-form video has revolutionized how cosmetic dentistry practices connect with potential patients. With platforms like TikTok, Instagram Reels, and YouTube Shorts commanding billions of daily views, cosmetic dentists who master this medium are seeing unprecedented growth in patient acquisition and brand awareness

Read more