From 56646d1178ccd2f6b1eece6a5b6d244edc17b837 Mon Sep 17 00:00:00 2001 From: Angelo Ashmore Date: Thu, 12 Oct 2023 18:39:50 -1000 Subject: [PATCH] fix(kit): support previews using a `/preview/` route prefix (#16) * fix(kit): update `redirectToPreviewURL()` to support the route prefix strategy * fix(kit): update `` to support the route prefix strategy * fix: correctly remove Prismic toolbar event handlers --- src/kit/PrismicPreview.svelte | 97 +++++++++++++++++++++++++++------ src/kit/redirectToPreviewURL.ts | 25 ++++++++- 2 files changed, 105 insertions(+), 17 deletions(-) diff --git a/src/kit/PrismicPreview.svelte b/src/kit/PrismicPreview.svelte index d315fb7..cfff946 100644 --- a/src/kit/PrismicPreview.svelte +++ b/src/kit/PrismicPreview.svelte @@ -1,7 +1,7 @@ diff --git a/src/kit/redirectToPreviewURL.ts b/src/kit/redirectToPreviewURL.ts index 9af043f..af9c063 100644 --- a/src/kit/redirectToPreviewURL.ts +++ b/src/kit/redirectToPreviewURL.ts @@ -1,4 +1,5 @@ import * as prismic from "@prismicio/client"; +import { Cookies } from "@sveltejs/kit"; export type RedirectToPreviewURLConfig = { /** @@ -16,11 +17,23 @@ export type RedirectToPreviewURLConfig = { */ request: Request; + /** + * The `cookies` object from a `+server` file. + * + * @see SvelteKit `+server` docs: \ + */ + cookies: Cookies; + /** * The default redirect URL if a URL cannot be determined for the previewed * document. */ defaultURL?: string; + + /** + * The route parameter prefixed during preview sessions. + */ + routePrefix?: string; }; /** @@ -49,6 +62,7 @@ export const redirectToPreviewURL = async ( new URL(config.request.url).searchParams.get("token") ?? undefined; const documentID = new URL(config.request.url).searchParams.get("documentId") ?? undefined; + const routePrefix = config.routePrefix ?? "preview"; const previewURL = await config.client.resolvePreviewURL({ previewToken, @@ -56,10 +70,19 @@ export const redirectToPreviewURL = async ( defaultURL: config.defaultURL || "/", }); + // Prevent a flash of non-preview content by setting the preview token + // on the initial page load. + if (previewToken) { + config.cookies.set(prismic.cookie.preview, previewToken, { + path: "/", + httpOnly: false, + }); + } + return new Response(undefined, { status: 307, headers: { - Location: previewURL, + Location: "/" + routePrefix + previewURL, }, }); };