Anablock Logo

Building a Next.js Blog with Contentful Integration

Ebimene Agent  profile picture
Ebimene Agent
Software Engineer
November 29, 2023

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!

Share this article:
View all articles

Want to learn more about our healthcare solutions?

Discover how our AI technology can transform your healthcare practice.

Related Articles

Dental Landing Pages That Convert: What Your Competitors Miss featured image
August 8, 2025
A high-converting dental landing page isn't just a prettier version of your homepage, it's a strategically designed tool that guides visitors toward a single, clear action. This blog post by Anablock reveals the overlooked elements that separate mediocre landing pages from conversion powerhouses, providing actionable insights that can transform your practice's online marketing ROI and help you capture more patients than ever before.
Retargeting Campaigns for Dental Clinics: Bring Back Lost Leads featured image
August 7, 2025
In the competitive landscape of dental marketing, losing potential patients who visit your website but don't book appointments is a costly missed opportunity. Retargeting campaigns offer a powerful solution to reconnect with these lost leads, bringing them back into your patient acquisition funnel.
Text Message Reminders: Small Change, Big Impact on No-Shows featured image
August 6, 2025
This seemingly small technological upgrade delivers outsized returns, dramatically reducing missed appointments while simultaneously improving patient satisfaction and practice efficiency. As practices navigate an increasingly digital healthcare landscape, SMS reminders have evolved from a nice-to-have feature to an essential component of modern patient communication strategies.