I wrote a quick middleware to enable auto-entering preview mode. It works by detecting (through rough heuristics) whether the link is a preview link, and then makes some assumptions, and forwards you on to the "enable preview" API url, which sets the cookie, then returns you to the page to be previewed. This eliminates the need for the CMS user to manually enable the preview mode using that drop down.
A limitation is that it doesn't work for root level pages - in my app, that's not a big deal because everything is localized. I'm sure there's a way to get it to work, but i wanted to share to see if there's any merit to this, or interest in helping to flesh it out.
Anyway, here it is:
import type { NextMiddleware } from "next/server";
import { NextResponse } from "next/server";
export const middleware: NextMiddleware = (req, ev) => {
const id = req.nextUrl.searchParams.get("_storyblok");
const space = req.nextUrl.searchParams.get("_storyblok_tk[space_id]");
// If there is an id and a space, it's probably a preview link
if (req.url.indexOf("?") && id && space) {
// We are going to reuse the URL that comes in from the request, but
// that URL will be regional, so we need to do some surgery to keep
// it from redirecting to a regionalized API url.
const url = req.nextUrl.clone();
url.pathname = `/api/preview`;
url.locale = "en";
url.search = `?secret=${process.env.STORYBLOK_PREVIEW_TOKEN}&slug=${req.nextUrl.locale}${req.nextUrl.pathname}`;
return NextResponse.redirect(url);
}
return NextResponse.next();
};
I wrote a quick middleware to enable auto-entering preview mode. It works by detecting (through rough heuristics) whether the link is a preview link, and then makes some assumptions, and forwards you on to the "enable preview" API url, which sets the cookie, then returns you to the page to be previewed. This eliminates the need for the CMS user to manually enable the preview mode using that drop down.
A limitation is that it doesn't work for root level pages - in my app, that's not a big deal because everything is localized. I'm sure there's a way to get it to work, but i wanted to share to see if there's any merit to this, or interest in helping to flesh it out.
Anyway, here it is:
Happy to make a PR if there's interest.