Skip to content

Commit

Permalink
fix: support App and Pages Router simultaneously
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed Oct 28, 2024
1 parent d28a81d commit b898eda
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/PrismicPreview.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Script from "next/script";
import { draftMode } from "next/headers";
import { useRouter as usePagesRouter } from "next/router";
import * as React from "react";
import * as prismic from "@prismicio/client";

Expand Down Expand Up @@ -46,23 +47,15 @@ export type PrismicPreviewProps = {
* This component can be wrapped around your app or added anywhere in your app's
* tree. It must be rendered on every page.
*/
export async function PrismicPreview({
export function PrismicPreview({
repositoryName,
children,
...props
}: PrismicPreviewProps): Promise<JSX.Element> {
}: PrismicPreviewProps): JSX.Element | Promise<JSX.Element> {
const toolbarSrc = prismic.getToolbarSrc(repositoryName);

let isDraftMode = false;
try {
isDraftMode = (await draftMode()).isEnabled;
} catch {
// noop - `requestAsyncStorage` propbably doesn't exist, such as
// in the Pages Router, which causes `draftMode()` to throw. We
// can ignore this case and assume Draft Mode is disabled.
}

return (
const result = (
<>
{children}
<PrismicPreviewClient
Expand All @@ -73,4 +66,29 @@ export async function PrismicPreview({
<Script src={toolbarSrc} strategy="lazyOnload" />
</>
);

// We need to check `draftMode()`, an async method, when running in the
// App Router. The Pages Router does not support async components, so we
// need to do some trickery to return a Promise in the App Router and
// unwrapped JSX in the Pages Router.
//
// Alternatively, we could serve a special server-only
// `<PrismicPreview>`, but that requires extra set up and depends on the
// compiler to recognize the `react-server` entry point. It is an
// undocumented feature that could be removed.
let isAppRouter = true;
try {
usePagesRouter();
isAppRouter = false;
} catch {}

if (isAppRouter) {
return new Promise(async (res) => {
isDraftMode = (await draftMode()).isEnabled;

res(result);
});
}

return result;
}

0 comments on commit b898eda

Please sign in to comment.