This article walks through setting up the Contentful Content Delivery API integration with your Next.js app. We have already created many content models that we are using on our pages. If you have not done so, you will need to create a content model and content in Contentful.
In order to use Contentful’s API we first need to grab our tokens. In the Contentful platform, go to Settings > API keys and there you’ll be able to copy the Space ID and Content Delivery API — access token.
Then go to your Next.js app and install Contentful.
yarn add contentful
.env.local file where you will set your tokens. I created variables that clearly identify that the tokens are for Contentful and named them
CONTENTFUL_ACCESS_TOKEN). This file will be ignored from Git as long as it’s included in your
.gitignore file, so your variables are kept secret.
(*Side note — any time you update an
env file you’ll want to restart your server to be able to access those variables you just created.)
Next update the
next.config.js file in order to use your env variables.
To help decrease the redundancy of creating a client instance on every page that was integrated with Contentful, I made a reusable module that can easily be imported on any page.
Then on the page you can just import the module with this one line.
Since the pages integrated with Contentful are statically served we are able to use the Next.js
getStaticProps function to pre-render the page at build time. Using
getStaticProps improves page load times because it fetches the data before it reaches the client.
getStaticProps can only be exported from a page and used as a standalone function.
The example page I will walk through is the Client Stories. On that page I imported the Contentful module to create a client instance, which allows access to many…