Set Up, Configure, And Get Started With Contentful Library In A Next.js Project
Introduction: What Is Contentful?
Contentful is a cloud-based headless CMS that helps businesses control their digital presence.
It’s an omni-channel content platform or an infrastructure that organises content and makes it scalable across multiple outlets. It lets you make, manage, and distribute content to any platform.
Contentful also provides you the complete freedom to build a custom content model. This helps you decide what content your business needs and manage it accordingly.
RESTful APIs help you distribute your content across various channels like:
- Websites
- Mobile apps (iOS, Android, and Windows phones)
- Smart devices
With an orderly UI, Contentful is a high-quality tool for creating, managing, and distributing your content online, on your own and as a team.
How Does Contentful Work?
Before Contentful, the only way to manage a cross-channel user experience was to create a content system for each channel using a separate CMS.
This approach makes updating and fixing websites a tedious and resource-consuming process.
Contentful unifies content management and distribution across all possible channels like web, mobile, or even IoT devices like smartwatches or smart TVs, in one editorial interface. Video, music, images, text, or other types of content can be managed and properly structured there.
Contentful has a three-step flow for publishing content in an app or on a website:
- First, you specify a content model, which is an essential step to properly structuring your content. The content model here is a space with content types that will represent only a particular kind of data. It can be text, images, location, or references. It stays independent from the presentation layer that displays the content.
For example, for a content model like “a blog post,” you will need text, a header image, in-line images, referral links, and videos that can all be set up together.
- Secondly, your internal or external editors should add entries and assets. Entries mean the content itself. It could be news, product features, or anything else your business needs to display. These entries will be arranged according to the previously created content model.
Assets, in this case, are images, audio, video, and other files attached to your content model. Your editor can manage all the content in a user-friendly and interactive editing interface.
- Finally, Contentful shows the content in a layout-independent way, so you can create pleasing solutions based on content creation and deliver them to the users as quickly as possible.
You’ll need to delegate content display management to developers or have someone help them, like designers or editors.
With the help of API Keys, you can determine which content will go to which platform.
When the delivery is finally set up, the only thing left is to hit ‘Publish.’ This tool will be completely adapted to your needs.
Most CMSs are optimized for working with only one dominant type of content, usually a website. These CMSs serve as website builders rather than holistic content management systems. They give you premade content models that limit the potential possibilities of CMS usage and are tied to only one presentation layer.
Contentful does it differently.
It offers a CMS that works with all types of content and their respective presentation layers, so the number of ways you can distribute the content is truly overwhelming.
How Do You Use Contentful?
To build a well-functioning Contentful-powered website, follow the steps listed below. The usual development process with Contentful looks like this:
- Log in to your Contentful account. Don’t have it yet? Sign up here.
- Create a new space, or “data bucket." It’s your place for content storage. This is where all the content related to a project is kept safely.
- Create a new content model. Add various types of content that will be saved to your space: text, images, SEO metadata, videos, etc.
- Let’s do some customizations! Structure all the content types in the order they should appear on the website.
For example:
- Importing data into the data bucket. Fill out the content model with the content you need.
- Get API keys from Contentful.
Under Settings, go to API keys from the header section to get your keys. And once you've got it, save it somewhere handy. You’re going to need them soon.
From here, make a couple of pages so that you have something to populate your project with
What Is Next.js?
Next.js is a JavaScript React framework that can be used to build pre-rendered React applications.
Along with a stellar developer experience, this framework offers developers both server-side rendering (SSR) and static-site generation.
Setting Up Contentful In Next.js
Before you begin, make sure you install contentful into your project:
yarn add contentful
Now, remember the Contentful API keys we asked you to save? You're going to need those to develop locally.
Make a .env.local
file at the top level of your project, and populate it with your keys:
.env.local
NEXT_PUBLIC_CONTENTFUL_SPACE_ID=your_id
NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN=your_access_token
NEXT_PUBLIC_CONTENTFUL_HOST=your_host
It’s time to use the Contentful client.
Make a new file called contentfulClient.ts
, and add the following code to it.
Note: We’ve put this in a utils/folder
, but you can choose to put it elsewhere and name it as per your preference.
/utils/contentfulClient.ts
import { createClient, Entry, FieldItem } from "contentful";
const contentfulClient = () => {
const client = createClient({
space: process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID || "",
accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN || "",
host: process.env.NEXT_PUBLIC_CONTENTFUL_HOST,
});
const getProducts = async () => {
try {
const entries = await client.getEntries({
content_type: "product",
});
const sanitizedEntries = entries.items.map((item: Entry<FieldItem>) => {
return { ...item.fields, id: item.sys.id };
});
return sanitizedEntries;
} catch (error) {
console.log(`Error fetching Products: ${error}`);
}
};
return { getProducts };
};
export default contentfulClient;
What's happening here? Let’s understand it from top to bottom:
- We're pulling in our API keys and making a Contentful client that we can use to pull in entries.
- We're making a
getProducts
function that callsclient.getEntries()
from Contentful (again, make sure you have some data to query). - We’re sanitizing the data as per our requirements.
- We're exporting this function to use in a
getStaticProps
function (keep reading, you'll see how)
Let's make an index.ts
file in the pages/products
directory that will use the data we pass to it.
/pages/products/index.ts
import { FieldItem } from "contentful";
import Image from "next/image";
import React from "react";
import contentfulClient from "../../utils/contentfulClient";
type productsType = {
products: {
description: string;
discount: number;
id: string;
images: FieldItem;
price: number;
quantity: number;
summary: string;
unit: string;
}[];
};
const Products = ({ products }: productsType) => {
return (
<div className="flex flex-col justify-center">
<h1 className="py-6 text-5xl text-center">Products Page</h1>
{products &&
products.map((product) => {
return (
<article key={product.id}>
<h3 className="text-2xl">{product.description}</h3>
<Image
alt="Grocery Product"
src={`http:${product.images[0].fields.file.url}`}
width={200}
height={200}
/>
<h6 className="text-2xl">{`Price: ${product.price}`}</h6>
<h6 className="text-2xl">{`Quantity: ${
product.quantity + product.unit
}`}</h6>
<p className="text-2xl">Product summary: {product.summary}</p>
</article>
);
})}
</div>
);
};
export async function getStaticProps() {
const { getProducts } = contentfulClient();
const products = await getProducts();
return {
props: {
products,
},
};
}
export default Products;
Notice how we're using getStaticProps
to fetch our API?
That means that the data is being pulled at the build time, so your users don't have to wait for posts to load.
How neat is that!
Also, because you’ve set up the webhook earlier, every new post will trigger a build for you without you having to rebuild the site yourself manually.
Note: If you are using images, then you’ll need to add the specific domain into next.config.js
. In our case, we added it like this:
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: ["images.ctfassets.net"],
},
};
module.exports = nextConfig;
And just like that, voilà, you have a Contentful-populated Next.js application.
Now go forth and make it your own. And don’t forget to share your learnings in the comments below!