Setting the file. One moment.
Chapter 08 · Contentful Next.js
Subchapter 8.1
references/nextjs-setup.mdMarkdown3 KBView on GitHub
Use this as the baseline setup for adding Contentful to an existing Next.js project.
If router type is not specified, use App Router patterns by default.
If you need to give version-specific setup or upgrade guidance, verify the current stable release first:
https://github.com/vercel/next.js/releasesnpm install contentfulAdd to .env.local:
CONTENTFUL_SPACE_ID=your_space_id
CONTENTFUL_ACCESS_TOKEN=your_cda_access_token
CONTENTFUL_PREVIEW_ACCESS_TOKEN=your_cpa_access_token
CONTENTFUL_ENVIRONMENT_ALIAS=master
# optional fallback if alias is not used
CONTENTFUL_ENVIRONMENT_ID=masterIf these values are missing, ask the user to add them to .env.local before continuing.
Where to find each value:
CONTENTFUL_SPACE_ID: in the Contentful URL (/spaces/<SPACE_ID>/...) or Space settings -> API keys.CONTENTFUL_ACCESS_TOKEN: from Space settings -> API keys (CDA token).CONTENTFUL_PREVIEW_ACCESS_TOKEN: from Space settings -> API keys (CPA token / Content Preview API).CONTENTFUL_ENVIRONMENT_ALIAS and CONTENTFUL_ENVIRONMENT_ID: Space settings -> Environments / environment aliases.Creating a single API key in Contentful gives both content delivery tokens:
CONTENTFUL_ACCESS_TOKENCONTENTFUL_PREVIEW_ACCESS_TOKEN// lib/contentful/client.ts
import { createClient } from "contentful";
export function createContentfulClient(preview = false) {
return createClient({
space: process.env.CONTENTFUL_SPACE_ID as string,
environment:
process.env.CONTENTFUL_ENVIRONMENT_ALIAS ||
process.env.CONTENTFUL_ENVIRONMENT_ID ||
"master",
accessToken: preview
? (process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN as string)
: (process.env.CONTENTFUL_ACCESS_TOKEN as string),
host: preview ? "preview.contentful.com" : undefined,
});
}// lib/contentful/queries.ts
import { createContentfulClient } from "./client";
export async function getEntryById(entryId: string, preview = false) {
const client = createContentfulClient(preview);
return client.getEntry(entryId);
}For production content, call with preview = false.
master) instead of hardcoding release environment IDs.