Next.js › Draft Mode & Preview Mode

How do you secure the route that enables Draft Mode so random visitors cannot use it?

Intermediate

Answer

You require a secret token as a query parameter when enabling Draft Mode, checking that the provided token matches a secret value stored in your environment variables before actually enabling it, ensuring only people with the correct secret link, usually shared by your CMS, can preview draft content.
export async function GET(request) {
  const secret = request.nextUrl.searchParams.get('secret');
  if (secret !== process.env.DRAFT_SECRET) {
    return new Response('Invalid token', { status: 401 });
  }
  const draft = await draftMode();
  draft.enable();
  return new Response('Draft mode enabled');
}
Real-world example A news organization protects its Draft Mode endpoint with a secret token stored in environment variables, so only links generated by their content management system can activate preview mode.

Common follow-ups: Where should this secret token be stored securely?;What happens if the secret token is leaked publicly?