Next.js + Contentful Tutorial
Follow a hands-on tutorial to learn the basics of Stackbit with a Next.js project using Contentful as the content source.
This tutorial takes a hands-on approach to learning Stackbit's core concepts using Next.js as the site framework and Contentful as the content source.
Before we move onto individual lessons, let's make sure that you can run the example project locally on your machine.
We suggest you also have the following to optimize your experience:
- Browser: Google Chrome
- Node: v14 or later
Setup Next.js Example Project
Let's begin by installing the example project, which is a Next.js + Contentful site:
npx create-stackbit-app@latest --example tutorial-nextjs-contentful cd tutorial-nextjs-contentful
This creates a new repo in a
tutorial-nextjs-contentful directory on your machine and installs the dependencies.
Setup and Connect Contentful
Next, we'll set up and connect Contentful to be sure the project can run properly before setting up Stackbit.
Create Contentful Space
After signing into or registering with Contentful, create a new community (free) space. Note that if you already have an active Contentful account, you may want to create an organization to place your new space. Choose the Web app only package.
Generate Management Token
If you don't already have a management token (also called a personal access token), you can generate one. Follow these steps from within the new empty space:
- Click Settings
- Choose API Keys
- Select the Content management tokens tab
- Click the button to generate a new token
Your new project already contains the content for the tutorial. You can import this into Contentful by running the setup command from within the new project directory.
npx cross-env CONTENTFUL_SPACE_ID=... CONTENTFUL_MANAGEMENT_TOKEN=... npm run setup
... with the appropriate values:
- Space ID can be found in the URL when inside a space.
- Management token is the token you just created (or referenced).
After this step, you should see content models and entries in Contentful.
Generate API Keys
From the same place you generated the management token, you can now generate API access keys.
- Select the content delivery / preview tokens
- Choose Add API key
Set Environment Variables
On your machine, duplicate
.env. Fill in the values:
CONTENTFUL_SPACE_ID="..." CONTENTFUL_DELIVERY_TOKEN="..." CONTENTFUL_PREVIEW_TOKEN="..."
The preview API key can be copied from the API screen you see after creating a new key.
Run the Project
Now you should be able to run the Next.js development server and see your content.
npm run dev
Visit localhost:3000 and you should see the example content you imported into your new Contentful space.