Next.js > Setting up Next.js Draft Mode

Setting up Next.js Draft Mode

Static rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on DatoCMS and want to view the draft immediately on your page.

Next.js has a feature called Draft Mode , which solves this problem. Here’s a guide on how to use it.

Step1: Create a draft mode API route

First, create a preview API route. It can have any name — e.g. app/api/draft/route.ts. In this API route, you must call draftMode().enable() to enable draft mode.

app/api/draft/route.js
import { draftMode } from 'next/headers';
export async function GET(request) {
draftMode().enable();
redirect('/');
}

You can manually test this route by accessing it via a browser at http://localhost:3000/api/draft. You’ll notice that you'll be redirected to the homepage, and the __prerender_bypass cookie will be set.

Step 2: Conditionally include draft records

Once draft mode is setup, your pages can check whether it is active or not with the draftMode().isEnabled property, and use this information to tweak the call to performRequest so that the includeDrafts flag is turned on.

This will instruct DatoCMS to return records at their latest version available instead of the currently published one:

1
import { draftMode } from 'next/headers';
2
3
export default async function Page() {
4
const { isEnabled } = draftMode();
5
6
const { data: { homepage } } = await performRequest(PAGE_CONTENT_QUERY, {
7
includeDrafts: isEnabled,
8
});
9
10
// [...]
11
}

You can read more details regarding draft mode on Next.js docs page.