Next.js with Contentful getStaticPaths
Generate static pages from Contentful entries with getStaticPaths.
When using Next.js with a headless CMS like Contentful you'll want a page for
every entry, like one page per blog post. You don't want to create a file for
each one by hand. This is what getStaticPaths is for. It tells Next.js which
pages to build from a dynamic route, and getStaticProps fetches the data for
each one.
Let's build this out with Next.js 10 and the Contentful JavaScript SDK.
Step 1: Set up a content type in Contentful
In your Contentful space, create a content type called Blog Post. Contentful
will give it the ID blogPost. Add three fields:
title: Short textslug: Short text (in the field settings you can mark it as unique)body: Rich text
Then add a couple of entries so we have something to fetch.
Step 2: Create the Contentful client
Create a new app and install the SDK:
npx create-next-app my-blogcd my-blognpm install contentful
Grab your Space ID and Content Delivery API access token from Settings → API
keys in Contentful and add them to .env.local:
# .env.localCONTENTFUL_SPACE_ID=your-space-idCONTENTFUL_ACCESS_TOKEN=your-access-token
These don't need the NEXT_PUBLIC_ prefix. They're only used in
getStaticPaths and getStaticProps, which run on the server, so they never
end up in the browser.
Now create a client we can reuse:
// lib/contentful.jsimport { createClient } from "contentful"const client = createClient({space: process.env.CONTENTFUL_SPACE_ID,accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,})export default client
Step 3: Create the dynamic route with getStaticPaths
Create pages/posts/[slug].js. The [slug] in the filename is the dynamic
part of the URL, so /posts/hello-world will have a slug param of
hello-world.
// pages/posts/[slug].jsimport client from "../../lib/contentful"export async function getStaticPaths() {const entries = await client.getEntries({content_type: "blogPost",select: "fields.slug",})const paths = entries.items.map((item) => ({params: { slug: item.fields.slug },}))return {paths,fallback: "blocking",}}
The select option tells Contentful to only return the slug field, since
that's all we need to build the paths. Each path is an object with a params
key that matches the name of the file, slug.
Setting fallback: "blocking" (new in Next.js 10) means a slug that wasn't
built ahead of time will be rendered on the server the first time someone
visits it, then cached as a static page. So when you publish a new post in
Contentful it shows up without a new deploy.
Note: getEntries returns 100 items by default. If you have more posts than
that, pass a limit (up to 1000) or page through them with skip.
Step 4: Fetch the post with getStaticProps
getStaticProps receives the params for each path. We can use the slug to
query for a single entry:
// pages/posts/[slug].js...export async function getStaticProps({ params }) {const entries = await client.getEntries({content_type: "blogPost","fields.slug": params.slug,limit: 1,})if (!entries.items.length) {return { notFound: true }}return {props: { post: entries.items[0].fields },revalidate: 60,}}
Filtering on "fields.slug" only works when content_type is also set. If no
entry matches, returning notFound: true (also new in Next.js 10) shows your
404 page. This is important with fallback: "blocking", otherwise any made up
slug would try to render a post that doesn't exist.
The revalidate option turns on Incremental Static Regeneration. Next.js will
regenerate the page in the background at most once every 60 seconds when it gets
a request, so edits in Contentful show up without rebuilding the whole site.
Step 5: Render the post
The rich text field comes back as a JSON document, not HTML. Contentful's renderer turns it into React components:
npm install @contentful/rich-text-react-renderer
// pages/posts/[slug].jsimport { documentToReactComponents } from "@contentful/rich-text-react-renderer"import client from "../../lib/contentful"const Post = ({ post }) => {return (<article><h1>{post.title}</h1>{documentToReactComponents(post.body)}</article>)}export default Postexport async function getStaticPaths() {...}export async function getStaticProps({ params }) {...}
Run npm run dev and visit localhost:3000/posts/your-slug to see the post.
When you run npm run build, you'll see each post from Contentful listed in the
build output as a static page.
By using getStaticPaths with Contentful we get fast static pages for every
post, and with fallback and revalidate they stay up to date without a
redeploy.
Have some feedback on this post? .