Next.js 13: Handling draftMode and Redirection

In this post, we'll be discussing a peculiar issue that developers might encounter while working with Next.js 13. Specifically, we're going to look at a problem where calling draftMode().enable() followed by a redirect() in a Next.js route handler doesn't set the __prerender_bypass cookie as expected.

Understanding the Issue

For a bit of context, Next.js provides a draftMode() function that, when enabled, sets a __prerender_bypass cookie. This cookie can be used to bypass static generation in development, enabling developers to preview drafts of their pages without having to rebuild their whole application.

However, it was discovered that if draftMode().enable() is followed by a redirect(), the cookie isn't set. This issue was confirmed and placed on the backlog for the Next.js team in May 2023.

Here's an example of a route handler that exhibits this behavior:

// app/api/demo/route.ts
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

export async function GET(req: Request) {
    return redirect("/");

When this handler is invoked, the expected __prerender_bypass cookie isn't set. This can cause unexpected behavior, especially when you're trying to develop and preview changes rapidly.

A Temporary Workaround

While we wait for a fix from the Next.js team, there is a workaround that seems to resolve the issue.

Instead of using the redirect() function, you can return a new Response object with a redirect status (307) and the Location header set to your redirect path:

return new Response(null, {
    status: 307,
    headers: {
        Location: path,

In this code, path should be replaced with the URL to which you wish to redirect.