UNPKG

@prismicio/next

Version:

Helpers to integrate Prismic into Next.js apps

1 lines 2.11 kB
{"version":3,"file":"getPreviewRef.cjs","names":["prismicCookie"],"sources":["../src/getPreviewRef.ts"],"sourcesContent":["import { cookie as prismicCookie } from \"@prismicio/client\"\n\n/**\n * Reads the Prismic preview ref for the current request when an active preview session exists.\n *\n * This is the read-side counterpart to `redirectToPreviewURL`, which writes the preview cookie. Use\n * it with Next.js Cache Components to read the ref _outside_ a cached function and pass it _in_ as\n * an argument so it becomes part of the cache key:\n *\n * @example\n * \t;```typescript\n * \timport { getPreviewRef } from \"@prismicio/next\"\n *\n * \tconst page = await fetchPage(uid, await getPreviewRef())\n * \t```\n *\n * @returns The active preview ref, or `undefined` if no preview session is active.\n * @experimental\n */\nexport async function getPreviewRef(): Promise<string | undefined> {\n\t// Need this to avoid the following Next.js build-time error:\n\t// You're importing a component that needs next/headers. That only works\n\t// in a Server Component which is not supported in the pages/ directory.\n\tconst { cookies, draftMode } = await import(\"next/headers\")\n\n\tlet isDraftModeEnabled = false\n\ttry {\n\t\tisDraftModeEnabled = (await draftMode()).isEnabled\n\t} catch {\n\t\t// `draftMode()` may have been called in a place that\n\t\t// does not have access to its async storage. This\n\t\t// occurs in places like `generateStaticParams()`. We\n\t\t// can ignore this case.\n\t\treturn\n\t}\n\tif (!isDraftModeEnabled) {\n\t\treturn\n\t}\n\n\tconst cookie = (await cookies()).get(prismicCookie.preview)?.value\n\tif (!cookie) {\n\t\treturn\n\t}\n\n\tconst isActiveCookie = cookie.includes(\"websitePreviewId=\")\n\tif (!isActiveCookie) {\n\t\treturn\n\t}\n\n\treturn cookie\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,gBAA6C;CAIlE,MAAM,EAAE,SAAS,cAAc,MAAM,OAAO;CAE5C,IAAI,qBAAqB;AACzB,KAAI;AACH,wBAAsB,MAAM,WAAW,EAAE;SAClC;AAKP;;AAED,KAAI,CAAC,mBACJ;CAGD,MAAM,UAAU,MAAM,SAAS,EAAE,IAAIA,kBAAAA,OAAc,QAAQ,EAAE;AAC7D,KAAI,CAAC,OACJ;AAID,KAAI,CADmB,OAAO,SAAS,oBAAoB,CAE1D;AAGD,QAAO"}