Draft Mode in Next.js is one of the important and attractive features of this popular framework that allows developers to preview website content without publishing it immediately. Simply put, this capability acts like a draft version of the program that lets them review and improve content without users seeing any changes that are not yet ready for publication.
To enable draft mode, you need to use the draftMode function which has been added to the API reference in the new versions of Next.js. This mode specifically allows you to work with server-side APIs and retrieve content temporarily without retention in the browser's history.
Enabling draft mode can help developers to preview website content in a draft format and make necessary changes before actual publication. This capability significantly reduces errors and enhances the user experience, allowing developers to ensure that their modifications are properly applied and that no issues arise in the publication process.
Here, we will look at how to use draft mode in Next.js step by step. You should note that for using this feature, you need to be using the new versions of this framework and refer to the provided documentation.
// Import the required function
import { draftMode } from 'next/headers';
// Function to enable draft mode
export async function GET(request) {
draftMode().enable();
return new Response('Draft mode enabled');
}
Line by Line Breakdown
// Import the required function
In this part of the code, the draftMode function is imported from the next/headers library so that we can use it for managing draft mode.
import { draftMode } from 'next/headers';
This statement imports the draftMode function specifically from the required library for its use in the code.
// Function to enable draft mode
This line defines a function that enables draft mode.
export async function GET(request) {
This section defines the server-side function to handle GET requests.
draftMode().enable();
This line activates draft mode so that you can preview the changes in a draft format.
return new Response('Draft mode enabled');
This line returns a response indicating that draft mode has been successfully enabled.