Create a Next.js and Buttercms App That Builds and Deploys with ZEIT Now

Deploy your Next.js and ButterCMS app with ZEIT Now in a serverless environment.

In this guide, you will discover how to create a Next.js app that displays links to posts from the ZEIT blog by utilizing the ButterCMS content management system, before deploying with a single command to ZEIT Now.

Next.js from ZEIT is a production-ready framework that helps you create fast React apps. ButterCMS is a drop-in headless CMS with zero headaches that allows you to never worry about hosting, upgrades, uptime, security or performance whilst storing all your content in one place.

By following this guide, you will create a clone of the example app, a starting point to get you up and running with your own Next.js + ButterCMS app in minutes.

Step 1: Create your ButterCMS Content

From your ButterCMS Collections dashboard, create a new Collection called Posts by clicking the + New Collection button.

Creating a Collection for your Next.js + ButterCMS project using the ButterCMS Collections dashboard.

Add the following fields to your Collection, all of type Short Text, by clicking the Add New Property button:

  • title
  • date
  • alt
  • image
  • url

Your Posts Collection should look like this:

An example Collection for your Next.js + ButterCMS project.

Next, click the + Add to Posts button to create a post, providing the relevant details.

That's it for creating content! You can edit both the Posts Collection and its content at any time, either by adding or removing Posts or changing the Collection Item Properties.

Next, select Settings from the account dropdown menu at the top left of the screen. Here you will find your Read API Token, make a note of this so you can use it later on in your app.

Step 2: Creating your Next.js App

Firstly, create a project directory and cd into it like so:

mkdir my-nextjs-buttercms-project && cd my-nextjs-buttercms-project

Creating and entering into the project directory.

Next, initialize your project, creating a package.json file in the process:

npm init -y

Initializing your project with a package.json file.

Note: Using the -y flag will initialize the created package.json file with these default settings.

Next, add the project dependencies:

npm i next react react-dom

Adding next, react and react-dom as dependencies to your project.

With the project initialized, create a /pages directory with a index.js file inside that uses the following code:

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

function HomePage() {
  const [posts, setPosts] = useState([])
  useEffect(() => {
    async function getPosts() {
      const res = await fetch(
        `https://api.buttercms.com/v2/content/?keys=posts&auth_token=${
          process.env.API_TOKEN
        }`
      )
      const { data } = await res.json()
      const allPosts = data.posts
      setPosts([...allPosts])
    }
    getPosts()
  }, [])
  return (
    <>
      <Head>
        <title>Next.js + ButterCMS</title>
        <link
          rel="stylesheet"
          href="https://css.zeit.sh/v1.css"
          type="text/css"
        />
      </Head>
      {posts.length > 0
        ? posts.map(p => (
            <Post
              alt={p.alt}
              date={p.date}
              key={p.title}
              image={p.image}
              title={p.title}
              url={p.url}
            />
          ))
        : null}
    </>
  )
}

export default HomePage

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

Let's take look at what this file achieves.

Inside the useEffect hook, an asynchronous function, getPosts, is defined, this is 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 + ButterCMS project.

Now that your page and component files have been created, the next step will show you how to add an environment variable to the project.

Step 3: Adding an Environment Variable

Add a now.json file at the root of your project directory with the following code:

{
  "build": {
    "env": {
      "BUTTER_API_TOKEN": "@butter_api_token"
    }
  }
}

An example now.json file for your Next.js + ButterCMS project.

With your now.json file created, you should add a next.config.js file at the root of your project directory with the code below:

module.exports = {
  env: {
    API_TOKEN: process.env.BUTTER_API_TOKEN
  }
}

An example next.config.js file for your Next.js + ButterCMS project.

The next.config.js file provides access to environment variables inside your Next.js app.

Now, add the following build script to your package.json file:

{
  ...
  "scripts": {
    "build": "next build"
  }
}

Adding a build script to your package.json file for your Next.js + ButterCMS project.

Next, you will make your API key available to your app during local development by creating a .env.build file.

Create a .env.build file at the root of your project directory with the following code, adding your API key obtained in step 1 where instructed:

BUTTER_API_TOKEN=your-api-token

An example .env.build file for your Next.js + ButterCMS project.

Lastly, to make your API key available for cloud deployment, create a Now Secret with the command below:

now secrets add BUTTER_API_TOKEN your-space-id

Adding the BUTTER_API_TOKEN secret to your project using Now Secrets.

With those steps out the way you are now able to run your app. You can develop your app locally using the following command:

next dev

Using the next dev command to run the app locally.

Step 4: Deploying the App

With your app ready, it is time to deploy it using a single command:

now

Using the now command to deploy your project to Now.

You will see a short build step in your terminal followed by the news that your project has been deployed, it should look similar to the example app.



Written By
Written by msweeneydevmsweeneydev
on June 21st 2019