Confusion among the three Contentful HTTP APIs is the most common reason why draft entries appear in production or editors' changes fail to save. Over more than 5 years of work, our engineers have seen dozens of projects where a single wrong token cost hours of debugging. Let's clarify how to distinguish between Delivery, Management, and Preview APIs, and provide ready-made configs for Next.js and Node.js.
How to distinguish the three Contentful APIs?
Content Delivery API (CDA) — read-only access to published content. Base URL: https://cdn.contentful.com. Token: delivery access token (read-only, can be committed to environment variables). Responses are cached on CDN — this yields TTFB under 100 ms when configured properly, which is 5x faster than without caching. Content Preview API (CPA) — read-only, but including drafts (unpublished entries). Base URL: https://preview.contentful.com. Token: preview access token. Used in Next.js Draft Mode / preview mode. Never use this token in production — otherwise the public will see unfinished articles. Content Management API (CMA) — full CRUD. Base URL: https://api.contentful.com. Token: personal access token or OAuth. Never used on the frontend. Only in backend scripts, admin panels, and CI/CD.
| API |
URL |
Token |
Purpose |
Caching |
| CDA |
cdn.contentful.com |
Delivery Token |
Public content |
CDN (controlled) |
| CPA |
preview.contentful.com |
Preview Token |
Drafts for editors |
None |
| CMA |
api.contentful.com |
Management Token |
CRUD content |
None |
How to choose the token for each environment?
In .env.local, always store three keys: CONTENTFUL_ACCESS_TOKEN_DELIVERY, CONTENTFUL_ACCESS_TOKEN_PREVIEW, and CONTENTFUL_MANAGEMENT_TOKEN. For production, use only Delivery. For staging — Preview. Management — only in local scripts and CI.
To avoid confusion, create separate .env.production and .env.staging files. In CI/CD, configure automatic token substitution based on branch name. This reduces human error risk. Practice shows: 90% of Contentful incidents are related to incorrect tokens.
Client setup
import { createClient } from 'contentful';
// Для продакшена
const deliveryClient = createClient({
space: process.env.CONTENTFUL_SPACE_ID!,
accessToken: process.env.CONTENTFUL_DELIVERY_TOKEN!,
});
// Для превью (Next.js Draft Mode)
const previewClient = createClient({
space: process.env.CONTENTFUL_SPACE_ID!,
accessToken: process.env.CONTENTFUL_PREVIEW_TOKEN!,
host: 'preview.contentful.com',
});
// Выбор клиента по флагу
export const getClient = (preview = false) =>
preview ? previewClient : deliveryClient;
Next.js Draft Mode + Preview API
// app/api/draft/route.ts
import { draftMode } from 'next/headers';
import { redirect } from 'next/navigation';
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const secret = searchParams.get('secret');
const slug = searchParams.get('slug');
if (secret !== process.env.CONTENTFUL_PREVIEW_SECRET) {
return new Response('Invalid token', { status: 401 });
}
draftMode().enable();
redirect(`/blog/${slug}`);
}
// В компоненте страницы
import { draftMode } from 'next/headers';
export default async function BlogPost({ params }) {
const { isEnabled } = draftMode();
const client = getClient(isEnabled);
const entry = await client.getEntries({
content_type: 'blogPost',
'fields.slug': params.slug,
});
}
CMA: programmatic content management
import { createClient } from 'contentful-management';
const cmaClient = createClient({
accessToken: process.env.CONTENTFUL_MANAGEMENT_TOKEN!,
});
const space = await cmaClient.getSpace(process.env.CONTENTFUL_SPACE_ID!);
const env = await space.getEnvironment('master');
// Создание записи
const entry = await env.createEntry('blogPost', {
fields: {
title: { 'en-US': 'New Post' },
slug: { 'en-US': 'new-post' },
},
});
// Публикация
await entry.publish();
Why is Preview API critical for editors?
Without Preview API, an editor cannot preview how an article will look before publishing. They are forced to publish "blind" and roll back errors. On one project, we implemented CPA and reduced content proofreading time by 40%: editors saw drafts directly on the staging domain via Draft Mode. Compared to manual export, Preview API reduces publishing errors by 3x.
Optimizing Contentful API requests
To avoid N+1 queries and reduce latency, use select and limit parameters: client.getEntries({ select: 'fields.title,fields.slug', limit: 50 }). For Delivery API, enable CDN caching (e.g., Cloudflare) with a TTL of up to 1 hour — this will boost LCP by 20%. For frequent queries, use ISR revalidation in Next.js. When working with drafts via Draft Mode, hydration mismatch may occur — solution: synchronize the token and space on server and client.
Environment configuration table
| Environment |
API |
Token |
Caching |
| production |
CDA |
Delivery |
CDN (TTL 1 hour) |
| staging |
CPA |
Preview |
None |
| local |
CMA |
Management |
None |
On a 401 error, check that the token matches the environment and has not expired. For CMA, ensure the Personal Access Token has permissions for the required space.
Turnkey setup process
- Analysis: gather requirements for locales, environments, content types.
- Design: define token schema, middleware for API selection.
- Implementation: write isolated clients for CDA, CPA, CMA.
- Testing: verify each token works in its environment, no draft leakage to production.
- Deployment: configure CI/CD for automatic token replacement during promotion.
Official Contentful Delivery API documentation.
Timeline: from 3 to 7 days depending on project complexity. Cost is calculated individually after auditing current integration. Content proofreading time savings — up to 40%.
What is included in the work
- Source code for the client module for CDA, CPA, CMA (TypeScript)
- Documentation on environment variables and tokens
- Draft Mode setup for editors
- Migration of existing queries to the new client
- Team training (1 hour online)
- Support for one month after integration
Common mistakes and checklist
- Using Preview Token in production → public cannot see new content.
- Lack of error handling (401/403) during token rotation.
- Storing Management Token in the repository.
- Always separate environments: production, staging, local.
- Use
.env.example with comments.
Order an integration audit from our engineers. Get a consultation on Contentful setup: we will check your current schema and suggest optimization. Over 5 years on the market, 50+ projects with Contentful — we guarantee the integration will go smoothly.
API Development with REST, GraphQL, WebSocket, and tRPC
A client comes to us with a Postman collection of 200 endpoints and says: 'Everything works, but the frontend is slow.' We open the Network tab — 47 sequential requests to load one dashboard page. Each one waits for the previous. This is not a server speed issue — it's an API architecture problem. With 10 years on the market, we've redesigned dozens of such integrations, and we guarantee: the right protocol and contract solve the problem at its root.
When REST stops being enough
REST works well for simple CRUD operations. But as soon as a mobile app appears alongside the web interface, over-fetching begins: the mobile app requests /api/users/123 and gets a 4KB object, but only needs name and avatar. Multiply that by a list of 50 users — 200KB traffic instead of 8KB.
GraphQL solves this with selection sets. The client describes exactly the fields it needs, and the server returns only those. On a project with React Native + Next.js, we migrated from REST to Apollo Server: payload size on the main screen dropped from 340KB to 28KB — a 92% traffic savings. Our certified engineers confirm: the typical pain when adopting GraphQL is N+1 query. A resolver for the author field on a post calls SELECT * FROM users WHERE id = ? for each post in the list. On a page with 20 posts — 21 database queries. Solved with DataLoader — it batches queries and turns them into one SELECT * FROM users WHERE id IN (...).
What is tRPC and how is it better than REST/GraphQL?
If the entire stack is TypeScript (Next.js + Node/Bun), tRPC removes a whole layer of problems. You define a procedure on the server — the client gets full type-safety automatically, without code generation and without Swagger. Renamed a field in the Zod schema — TypeScript highlights all places on the frontend where it's used. tRPC reduces code by 2 times compared to REST + Swagger + openapi-typescript: no need to maintain a separate specification and generate types — everything is inferred from runtime validators. However, tRPC is not suitable if the API is consumed by third-party clients or mobile apps in other languages — in such cases we use GraphQL or REST with OpenAPI specification.
WebSocket and real-time: when SSE, when WS?
HTTP polling every 5 seconds is an illusion of real-time with up to 5 seconds delay and useless server load. For chats, live notifications, collaborative editing — WebSocket or Server-Sent Events. SSE is a one-way stream from server to client, works over ordinary HTTP, automatically reconnects. Suitable for notifications, data streaming, progress bars. WebSocket is bidirectional, needed for chats and collaborative features. Experience shows: 80% of 'real-time' tasks are solved with SSE, not WebSocket — fewer infrastructure complexities.
A typical mistake: opening a WebSocket connection for each page component. On one project, the dashboard opened 12 parallel WS connections. The correct approach is one connection manager at the application level, subscriptions through it. In our work results, we always transfer the connection scheme and a ready solution.
| Protocol |
Typing |
Over-fetching |
Versioning |
Real-time |
| REST |
Weak (OpenAPI) |
Yes |
URL / Header |
Polling |
| GraphQL |
Strong (SDL) |
No |
Deprecation |
Subscriptions |
| tRPC |
Full (TypeScript) |
No |
TypeScript checks |
Subscriptions (optional) |
Swagger / OpenAPI as a contract
Documentation written after the fact becomes outdated the day after release. We write the OpenAPI 3.1 specification before development starts; it becomes the contract between frontend and backend. The frontend generates types via openapi-typescript, the backend validates incoming data using generated schemas. Contract deviation from implementation is caught on CI, not during review. For Laravel — l5-swagger or dedoc/scramble. For Node.js — @fastify/swagger or Zod + zod-to-openapi.
How to properly authenticate an API?
JWT with long-lived access tokens without rotation is a source of problems when compromised. The correct scheme: access token for 15 minutes, refresh token for 30 days with rotation on each use. Refresh token stored in an httpOnly cookie, access token in memory (not in localStorage). For inter-service communication — API Keys with scope limitations or mTLS. OAuth 2.0 with PKCE for public clients (SPA, mobile).
How to handle versioning and backward compatibility?
Breaking changes in an API without versioning break clients. Three approaches we use in projects:
| Method |
Example |
When to use |
| URL versioning |
/api/v2/ |
REST API with long-term legacy support |
| Header versioning |
Accept: application/vnd.api+json;version=2 |
Minimal URL changes |
| Evolutionary (deprecation) |
Adding fields, GraphQL deprecated directive |
For GraphQL — smooth field removal |
We guarantee backward compatibility through automated checks (oasdiff) on CI.
How we develop APIs: step-by-step plan
-
Analysis — audit of current integrations, data schema compilation, protocol selection (REST/GraphQL/tRPC/WebSocket).
-
Contract design — OpenAPI or SDL (GraphQL) before the first line of code.
-
Development — implementation per contract, unit tests for each endpoint.
-
Load testing — k6: 500 virtual users, 10 minutes, p95 latency ≤ 200ms.
-
Deployment — CI/CD with backward compatibility check, automatic documentation publication.
-
Team training — handover of Postman collection or Playground, connection instructions.
Typical mistakes we eliminate
- N+1 on queries without DataLoader.
- No rate limiting — DDOS through unauthenticated endpoints.
- Storing access token in localStorage.
- Opening multiple WebSocket connections instead of a single connection manager.
- Documentation not updated after release.
What is included (deliverables)
- OpenAPI 3.1 specification (or SDL for GraphQL).
- Generated client types for TypeScript / Dart / Kotlin.
- Set of automated tests covering all endpoints (unit + integration).
- Load tests (k6) and report (p50/p95/p99 latency, RPS).
- Documentation in Swagger UI / Redoc / GraphiQL.
- Team training (2–4 hour workshop).
- Support for 30 days after delivery (per contract).
Our experience
-
10+ years in the API development market.
-
200+ completed projects (REST, GraphQL, WebSocket, tRPC).
-
50+ certified engineers (AWS, Kubernetes, API Design).
- Traffic savings averaging 85% when migrating from REST to GraphQL for mobile apps.
-
100% backward compatibility — not a single broken client in the last 3 years.
Timeline
API development for a typical SaaS project with 30–50 endpoints: from 3 to 8 weeks depending on business logic complexity and number of external integrations. Migration of an existing REST API to GraphQL: from 2 to 6 weeks. Adding a WebSocket layer to an existing backend: from 1 to 3 weeks. Cost is calculated individually after an audit. Get a consultation — contact us to discuss your project.