Create a Next.js App with Contentful and Deploy It with Vercel

Deploy your Next.js and Contentful app with Vercel in a serverless environment.

In this guide, you will discover how to create a Next.js app that displays links to posts from the Vercel blog by utilizing the Contentful client, before deploying to Vercel.

Next.js from Vercel is a production-ready framework that helps you create fast React apps. Contentful is a powerful headless CMS that allows you to rapidly create, manage and distribute content to any platform you like.

By following this guide, you will create an app similar to this example app — a starting point to get you up and running with your own Next.js + Contentful app in minutes.

Step 1: Create your Contentful Content

From your Contentful dashboard, create a new space. Head to the Content Model section and create a new Content Type called Post by clicking the Add content type button.

Creating a Content Model for your Next.js + Contentful project using the Contentful dashboard.

Add the following fields to your Content Model, all of type Short Text, by clicking the Add field button:

  • title
  • date
  • alt
  • image
  • url

Your Post Content Model should look like this:

An example Content Model for your Next.js + Contentful project.

Next, using the Content tab, click the Add Post button to create a post, providing the relevant details (e.g. Vercel blog URL, an image href atribute, etc.).

That's it for setting up you content structure! You can edit both the Content and Content Model at any time, giving you complete flexibility over your content.

Next, you will create a set of API keys for use in your app, this will allow you to connect to the Contentful Client to request your posts.

Step 2: Create API keys

Click the Settings tab and choose the API Keys option, then click the Add API Key button.

Note: Use separate keys for each platform you need to deliver content to.

With the keys created, make a note of both the Space ID and the Content Delivery API - access token, these will be used later on. The Content Delivery API access token is a read-only token and can be used safely in your frontend applications.

That's all the setup required for Contentful, within just a few minutes you have managed to create a Content Model, add content, and generate a set of API keys.

In the next step, you will create your Next.js app.

Step 3: Create your Next.js App

To display your new blog and content, create a new Next.js application by using create-next-app:

npm init next-app my-nextjs-contentful-project

Bootstrapping a Next.js application from your command line.

Enter inside the project directory, install the contentful package, and start the development server:

cd my-nextjs-contentful-project && yarn add contentful && yarn dev

Moving to your project, installing dependencies, and starting a local development server from the command line.

Next, go to pages/index.js — that is, the component that renders the homepage of the project — and replace its contents with the following code:

import { useEffect, useState } from 'react'
import Head from 'next/head'
import Post from '../components/post'

const client = require('contentful').createClient({
  space: process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID,
  accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN,
})

function HomePage() {
  async function fetchEntries() {
    const entries = await client.getEntries()
    if (entries.items) return entries.items
    console.log(`Error getting Entries for ${contentType.name}.`)
  }

  const [posts, setPosts] = useState([])

  useEffect(() => {
    async function getPosts() {
      const allPosts = await fetchEntries()
      setPosts([...allPosts])
    }
    getPosts()
  }, [])

  return (
    <>
      <Head>
        <title>Next.js + Contentful</title>
        <link
          rel="stylesheet"
          href="https://css.zeit.sh/v1.css"
          type="text/css"
        />
      </Head>
      {posts.length > 0
        ? posts.map((p) => (
            <Post
              alt={p.fields.alt}
              date={p.fields.date}
              key={p.fields.title}
              image={p.fields.image}
              title={p.fields.title}
              url={p.fields.url}
            />
          ))
        : null}
    </>
  )
}

export default HomePage

An example index.js page for your Next.js + Contentful project.

Let's take look at what this file achieves.

Firstly, it requires the contentful dependency and creates a client, this provides access to many useful helper methods for retrieving content from Contentful.

Inside the HomePage function, two asynchronous functions are defined, these are then called in the useEffect hook to retrieve the posts on initial load.

With the posts retrieved, they are then mapped over to be displayed with a <Post> component that you will create next.

Create a /components directory that contains a post.js file with the following content:

function Post({ alt, date, image, title, url }) {
  return (
    <div className="container">
      <a href={url}>
        <img alt={alt} src={image} />
      </a>
      <div className="text">
        <h2>{title}</h2>
        <h4>{date}</h4>
      </div>
      <style jsx>{`
        .container {
          cursor: pointer;
          height: 453px;
          margin-bottom: 48px;
        }
        a {
          border-bottom: none;
        }
        a:hover {
          border-bottom: none;
        }
        .text {
          margin-top: -160px;
          padding: 24px;
          position: absolute;
        }
        h2 {
          color: white;
          font-size: 24px;
          margin-bottom: 0;
        }
        h4 {
          color: rgba(255, 255, 255, 0.8);
          font-size: 16px;
          font-weight: 500;
          margin-top: 8px;
        }
      `}</style>
    </div>
  )
}

export default Post

An example post.js component for your Next.js + Contentful project.

Now that your page and component files have been created, you can set the Environment Variables inside a .env.local file:

echo 'NEXT_PUBLIC_CONTENTFUL_SPACE_ID=<YOUR_SPACE_ID>\nNEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN=<YOUR_ACCESS_TOKEN>' >> .env.local

Creating environment variables in a `env.local` file.

Step 4: Deploy

To deploy your Next.js + Contentful app with a Vercel for Git, make sure it has been pushed to a Git repository.

During the import process, you will need to add the following environment variables:

  • NEXT_PUBLIC_CONTENTFUL_SPACE_ID
  • NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN

Import the project into Vercel using your Git of choice:

After your project has been imported, all subsequent pushes to branches will generate Preview Deployments, and all changes made to the Production Branch (commonly "main") will result in a Production Deployment.



Written By
Written by mcsdevmcsdev
Last Edited on July 17th 2020