Integrating Next.js and Contentful for your Headless CMS

Next.js and React are popular choices for building web applications. When paired with a headless CMS like Contentful, they offer a powerful combination of flexibility, ease of use, and performance. This guide will help you integrate a Next.js application with Contentful.

Why Next.js and React?

A headless CMS, like Contentful, allows you to separate the content management and presentation layers of your web application. This means that you can manage your content in one place, and then use that content to power any number of different front-end experiences, such as a web or mobile application.

Next.js is a React framework for the web, enabling you to create full-stack web applications. Used by some of the largest companies in the world, it integrates the latest React features, includes built-in image, font, and script optimizations, and has powerful Rust-based JavaScript tooling for the fastest builds and local environment.

React, on the other hand, is a JavaScript library for building user interfaces. It allows you to build reusable components that can be easily shared across different parts of your app. Next.js is a React framework, so you can use your existing React knowledge when working with Next.js.

When used together, Next.js and React allow you to create a performant and scalable web app that can easily consume and display content from a headless CMS like Contentful. This makes it easy to manage your content and keep your web app up to date without having to worry about the underlying infrastructure.

Getting Started

To help you get started quickly, we’ve built a template using Next.js, Contentful, and Tailwind CSS, which you can easily clone to your machine.

npx create-next-app --example cms-contentful cms-contentful-app
cd cms-contentful-app
Clone the Next.js and Contentful starter template on your local machine.

Next, you’ll need to create a new account on Contentful and make an empty “space”. This is where your content lives. We’ve also created a sample content model to help you get started quickly.

You will need your Space ID and you will need to create a Content Management Token. You can find your Space ID in the Contentful app in Settings under API Keys. Click on Add API key.

You will also need to create a Content Management API token. Avoid sharing this token because it allows both read and write access to your Contentful space. Once the token is generated copy the key and save remotely as it will not be accessible later on. If lost, a new one must be created.

Use your Space ID and Content Management Token in the command below to import the pre-made content model into your space using our setup Node.js script:

npx cross-env CONTENTFUL_SPACE_ID=YOUR_SPACE_ID CONTENTFUL_MANAGEMENT_TOKEN=XXX npm run setup
Run the setup script to create the content models in Contentful.

Adding Content in Contentful

Now that you’ve created your space in Contentful, add some content! You’ll notice the new author and post entries for the example we’ve provided. Publish each entry to make this fully live.

Now, let’s save the Space ID and token from earlier to add as Environment Variables for running locally. Create a new .env.local file in your application:

CONTENTFUL_SPACE_ID='your-space-id'
CONTENTFUL_ACCESS_TOKEN='your-content-api-token'
Example .env.local file with the values from Contentful.

Then, you can start your application with npm install && npm run dev. Your project should now be running on http://localhost:3000.

How It Works

Next.js is designed to integrate with any data source of your choice, including Content Management Systems. Contentful provides a helpful GraphQL API, which you can both query and mutate data from. This allows you to decouple your content from your frontend. For example:

async function fetchGraphQL(query) {
return fetch(
`https://graphql.contentful.com/content/v1/spaces/${process.env.CONTENTFUL_SPACE_ID}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.CONTENTFUL_ACCESS_TOKEN}`,
},
body: JSON.stringify({ query }),
}
).then((response) => response.json());
}
A fetch to the Contentful GraphQL API.

This code allows you to fetch data on the server from your Contentful instance. Each space inside Contentful has it’s own ID (e.g. CONTENTFUL_SPACE_ID) which you can add as an Environment Variable inside your Next.js application. This allows you to use secure values you don’t want to commit to git, which are only evaluated on the server (e.g. CONTENTFUL_ACCESS_TOKEN).

Deploying to Vercel

Now that you have your application, you can easily deploy to Vercel to get your site online. You can either use the Vercel CLI of the git integrations to deploy your code. Let’s use the git integration.

  1. Push your code to your git repository (e.g. GitHub, GitLab, or BitBucket).
  2. Import your project into Vercel.
  3. Vercel will detect that you are using Next.js and will enable the correct settings for your deployment.
  4. Add your Environment Variables from your .env.local file during the deployment process.
  5. Your application is now deployed!

Alternatively, you can click “Deploy” from here and start a brand new repository.

Summary

In summary, by using Next.js and React with Contentful you can benefit from:

  • A headless CMS, which gives you the ability to manage your content in one place, and then use that content to power any number of different front-end experiences.
  • Next.js, which offers features like automatic code splitting and server-side rendering, which can help improve the performance and SEO of your web app.
  • React, which allows you to build reusable components that can be easily shared across different parts of your app.

The combination of Next.js with Contentful gives you the power to quickly build scalable dynamic static websites with improved search engine optimization (SEO) and enhanced performance.

Couldn't find the guide you need?