Building a Next.js Blog with Contentful Integration

Ebimene Agent
Software Engineer
November 29, 2023

Blog image

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

Related Articles

Choosing the Right Data Sources for Training AI Chatbots featured image
December 12, 2025
If your AI chatbot sounds generic, gives wrong answers, or feels unreliable, the problem is probably not the model. It is the data behind it. In this article, you will see why choosing the right data sources matters more than any tool or framework. We walk through what data your chatbot should actually learn from, which sources help it sound accurate and confident, which ones quietly break performance, and how to use your existing knowledge without creating constant maintenance work. If you want a chatbot that truly reflects how your business works, this is where you need to start.
Lead Qualification Made Easy with AI Voice Assistants featured image
December 11, 2025
If your sales team is spending hours chasing leads that never convert, this is for you. Most businesses do not have a lead problem, they have a qualification problem. In this article, you will see how AI voice assistants handle the first conversation, ask the right questions, and surface only the leads worth your team’s time. You will learn how voice AI actually works, where it fits into real sales workflows, and why companies using it respond faster, close more deals, and stop wasting effort on unqualified prospects. If you want your leads filtered before they ever reach sales, keep reading.
The Automation Impact on Response Time and Conversions Is Bigger Than Most Businesses Realize featured image
December 9, 2025
This blog explains how response time has become one of the strongest predictors of conversions and why most businesses lose revenue not from poor marketing, but from slow follow up. It highlights how automation eliminates the delays that humans cannot avoid, ensuring immediate engagement across chat, voice, and form submissions. The post shows how automated systems capture intent at its peak, create consistent customer experiences, and significantly increase conversion rates by closing the gap between inquiry and response. Automation does not just improve speed. It transforms how the entire pipeline operates.

Unlock the Full Power of AI-Driven Transformation

Schedule a Demo

See how Anablock can automate and scale your business with AI.

Book Now

Start a Voice Call

Talk directly with our AI experts and get real-time guidance.

Call Now

Send us a Message

Summarize this page content with AI