How do you fetch draft or unpublished content differently from published content when Draft Mode is enabled?
Short answer
You check whether Draft Mode is currently enabled inside your data fetching function, and if it is, you request the draft version of the content from your content management system's API instead of the published version, usually by passing a different query parameter or using a…
Advertisement
AModel answer
You check whether Draft Mode is currently enabled inside your data fetching function, and if it is, you request the draft version of the content from your content management system's API instead of the published version, usually by passing a different query parameter or using a preview specific API token.
import { draftMode } from 'next/headers';
async function getPost(slug) {
const { isEnabled } = await draftMode();
const url = isEnabled
? `https://cms.example.com/posts/${slug}?preview=true`
: `https://cms.example.com/posts/${slug}`;
const res = await fetch(url);
return res.json();
}Real-world example
A blog checks if Draft Mode is enabled before deciding whether to request the published or the draft version of an article from its headless CMS, giving editors an accurate live preview.
Likely follow-ups
- What security measures should protect the endpoint that enables Draft Mode?
- Can regular visitors accidentally trigger Draft Mode?
Related topics