@prismicio/next 1.7.1 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +5 -3
  2. package/dist/PrismicNextImage.d.ts +7 -8
  3. package/dist/PrismicNextImage.js +8 -8
  4. package/dist/PrismicNextImage.js.map +1 -1
  5. package/dist/PrismicNextLink.d.ts +99 -100
  6. package/dist/PrismicNextLink.js +3 -5
  7. package/dist/PrismicNextLink.js.map +1 -1
  8. package/dist/PrismicPreview.d.ts +5 -13
  9. package/dist/PrismicPreview.js +6 -19
  10. package/dist/PrismicPreview.js.map +1 -1
  11. package/dist/PrismicPreviewClient.d.ts +5 -3
  12. package/dist/PrismicPreviewClient.js +58 -69
  13. package/dist/PrismicPreviewClient.js.map +1 -1
  14. package/dist/createLocaleRedirect.d.ts +8 -15
  15. package/dist/createLocaleRedirect.js +4 -28
  16. package/dist/createLocaleRedirect.js.map +1 -1
  17. package/dist/enableAutoPreviews.d.ts +7 -31
  18. package/dist/enableAutoPreviews.js +24 -35
  19. package/dist/enableAutoPreviews.js.map +1 -1
  20. package/dist/exitPreview.d.ts +4 -46
  21. package/dist/exitPreview.js +8 -15
  22. package/dist/exitPreview.js.map +1 -1
  23. package/dist/imgixLoader.js.map +1 -1
  24. package/dist/index.d.ts +15 -18
  25. package/dist/index.js +2 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/devMsg.d.ts +1 -1
  28. package/dist/lib/devMsg.js.map +1 -1
  29. package/dist/package.json.js +1 -1
  30. package/dist/pages/PrismicPreview.d.ts +31 -0
  31. package/dist/pages/PrismicPreview.js +64 -0
  32. package/dist/pages/PrismicPreview.js.map +1 -0
  33. package/dist/pages/enableAutoPreviews.d.ts +31 -0
  34. package/dist/pages/enableAutoPreviews.js +19 -0
  35. package/dist/pages/enableAutoPreviews.js.map +1 -0
  36. package/dist/pages/exitPreview.d.ts +33 -0
  37. package/dist/pages/exitPreview.js +10 -0
  38. package/dist/pages/exitPreview.js.map +1 -0
  39. package/dist/pages/index.d.ts +18 -0
  40. package/dist/pages/redirectToPreviewURL.d.ts +43 -0
  41. package/dist/pages/redirectToPreviewURL.js +16 -0
  42. package/dist/pages/redirectToPreviewURL.js.map +1 -0
  43. package/dist/{setPreviewData.d.ts → pages/setPreviewData.d.ts} +3 -9
  44. package/dist/{setPreviewData.js → pages/setPreviewData.js} +2 -2
  45. package/dist/pages/setPreviewData.js.map +1 -0
  46. package/dist/pages/types.d.ts +30 -0
  47. package/dist/pages.js +21 -0
  48. package/dist/pages.js.map +1 -0
  49. package/dist/redirectToPreviewURL.d.ts +11 -41
  50. package/dist/redirectToPreviewURL.js +16 -22
  51. package/dist/redirectToPreviewURL.js.map +1 -1
  52. package/dist/types.d.ts +2 -51
  53. package/package.json +61 -54
  54. package/src/PrismicNextImage.tsx +19 -16
  55. package/src/PrismicNextLink.tsx +17 -13
  56. package/src/PrismicPreview.tsx +20 -50
  57. package/src/PrismicPreviewClient.tsx +111 -138
  58. package/src/createLocaleRedirect.ts +14 -56
  59. package/src/enableAutoPreviews.ts +38 -110
  60. package/src/exitPreview.ts +18 -81
  61. package/src/index.ts +15 -26
  62. package/src/lib/devMsg.ts +1 -1
  63. package/src/pages/PrismicPreview.tsx +145 -0
  64. package/src/pages/enableAutoPreviews.ts +62 -0
  65. package/src/pages/exitPreview.ts +45 -0
  66. package/src/pages/index.ts +27 -0
  67. package/src/pages/redirectToPreviewURL.ts +77 -0
  68. package/src/{setPreviewData.ts → pages/setPreviewData.ts} +5 -11
  69. package/src/pages/types.ts +36 -0
  70. package/src/redirectToPreviewURL.ts +44 -95
  71. package/src/types.ts +2 -56
  72. package/dist/PrismicNextImage.cjs +0 -64
  73. package/dist/PrismicNextImage.cjs.map +0 -1
  74. package/dist/PrismicNextLink.cjs +0 -40
  75. package/dist/PrismicNextLink.cjs.map +0 -1
  76. package/dist/PrismicPreview.cjs +0 -28
  77. package/dist/PrismicPreview.cjs.map +0 -1
  78. package/dist/PrismicPreviewClient.cjs +0 -81
  79. package/dist/PrismicPreviewClient.cjs.map +0 -1
  80. package/dist/_node_modules/@prismicio/client/dist/cookie.cjs +0 -5
  81. package/dist/_node_modules/@prismicio/client/dist/cookie.cjs.map +0 -1
  82. package/dist/_node_modules/@prismicio/client/dist/cookie.js +0 -5
  83. package/dist/_node_modules/@prismicio/client/dist/cookie.js.map +0 -1
  84. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.cjs +0 -16
  85. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.cjs.map +0 -1
  86. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.js +0 -16
  87. package/dist/_node_modules/@prismicio/client/dist/errors/PrismicError.js.map +0 -1
  88. package/dist/_node_modules/@prismicio/client/dist/getToolbarSrc.cjs +0 -13
  89. package/dist/_node_modules/@prismicio/client/dist/getToolbarSrc.cjs.map +0 -1
  90. package/dist/_node_modules/@prismicio/client/dist/getToolbarSrc.js +0 -13
  91. package/dist/_node_modules/@prismicio/client/dist/getToolbarSrc.js.map +0 -1
  92. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.cjs +0 -47
  93. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.cjs.map +0 -1
  94. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.js +0 -47
  95. package/dist/_node_modules/@prismicio/client/dist/helpers/asLink.js.map +0 -1
  96. package/dist/_node_modules/@prismicio/client/dist/helpers/asLinkAttrs.cjs +0 -28
  97. package/dist/_node_modules/@prismicio/client/dist/helpers/asLinkAttrs.cjs.map +0 -1
  98. package/dist/_node_modules/@prismicio/client/dist/helpers/asLinkAttrs.js +0 -28
  99. package/dist/_node_modules/@prismicio/client/dist/helpers/asLinkAttrs.js.map +0 -1
  100. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.cjs +0 -27
  101. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.cjs.map +0 -1
  102. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.js +0 -27
  103. package/dist/_node_modules/@prismicio/client/dist/helpers/documentToLinkField.js.map +0 -1
  104. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.cjs +0 -14
  105. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.cjs.map +0 -1
  106. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.js +0 -14
  107. package/dist/_node_modules/@prismicio/client/dist/helpers/isFilled.js.map +0 -1
  108. package/dist/_node_modules/@prismicio/client/dist/isRepositoryName.cjs +0 -7
  109. package/dist/_node_modules/@prismicio/client/dist/isRepositoryName.cjs.map +0 -1
  110. package/dist/_node_modules/@prismicio/client/dist/isRepositoryName.js +0 -7
  111. package/dist/_node_modules/@prismicio/client/dist/isRepositoryName.js.map +0 -1
  112. package/dist/_node_modules/@prismicio/client/dist/lib/isInternalURL.cjs +0 -9
  113. package/dist/_node_modules/@prismicio/client/dist/lib/isInternalURL.cjs.map +0 -1
  114. package/dist/_node_modules/@prismicio/client/dist/lib/isInternalURL.js +0 -9
  115. package/dist/_node_modules/@prismicio/client/dist/lib/isInternalURL.js.map +0 -1
  116. package/dist/_node_modules/@prismicio/client/dist/types/value/link.cjs +0 -10
  117. package/dist/_node_modules/@prismicio/client/dist/types/value/link.cjs.map +0 -1
  118. package/dist/_node_modules/@prismicio/client/dist/types/value/link.js +0 -10
  119. package/dist/_node_modules/@prismicio/client/dist/types/value/link.js.map +0 -1
  120. package/dist/createLocaleRedirect.cjs +0 -32
  121. package/dist/createLocaleRedirect.cjs.map +0 -1
  122. package/dist/enableAutoPreviews.cjs +0 -40
  123. package/dist/enableAutoPreviews.cjs.map +0 -1
  124. package/dist/exitPreview.cjs +0 -20
  125. package/dist/exitPreview.cjs.map +0 -1
  126. package/dist/imgixLoader.cjs +0 -17
  127. package/dist/imgixLoader.cjs.map +0 -1
  128. package/dist/index.cjs +0 -21
  129. package/dist/index.cjs.map +0 -1
  130. package/dist/lib/devMsg.cjs +0 -8
  131. package/dist/lib/devMsg.cjs.map +0 -1
  132. package/dist/lib/getPreviewCookieRepositoryName.cjs +0 -7
  133. package/dist/lib/getPreviewCookieRepositoryName.cjs.map +0 -1
  134. package/dist/lib/getPreviewCookieRepositoryName.d.ts +0 -9
  135. package/dist/lib/getPreviewCookieRepositoryName.js +0 -7
  136. package/dist/lib/getPreviewCookieRepositoryName.js.map +0 -1
  137. package/dist/lib/getPrismicPreviewCookie.cjs +0 -21
  138. package/dist/lib/getPrismicPreviewCookie.cjs.map +0 -1
  139. package/dist/lib/getPrismicPreviewCookie.d.ts +0 -9
  140. package/dist/lib/getPrismicPreviewCookie.js +0 -21
  141. package/dist/lib/getPrismicPreviewCookie.js.map +0 -1
  142. package/dist/package.json.cjs +0 -5
  143. package/dist/package.json.cjs.map +0 -1
  144. package/dist/redirectToPreviewURL.cjs +0 -30
  145. package/dist/redirectToPreviewURL.cjs.map +0 -1
  146. package/dist/setPreviewData.cjs +0 -11
  147. package/dist/setPreviewData.cjs.map +0 -1
  148. package/dist/setPreviewData.js.map +0 -1
  149. package/src/lib/getPreviewCookieRepositoryName.ts +0 -14
  150. package/src/lib/getPrismicPreviewCookie.ts +0 -33
@@ -0,0 +1,145 @@
1
+ import { type ReactNode, useEffect, JSX } from "react";
2
+ import { useRouter } from "next/router";
3
+ import Script from "next/script";
4
+ import { getToolbarSrc, cookie as prismicCookie } from "@prismicio/client";
5
+
6
+ /** Props for `<PrismicPreview>`. */
7
+ export type PrismicPreviewProps = {
8
+ /**
9
+ * The name of your Prismic repository. A Prismic Toolbar will be registered
10
+ * using this repository.
11
+ */
12
+ repositoryName: string;
13
+
14
+ /**
15
+ * The URL of your app's Prismic preview endpoint (default: `/api/preview`).
16
+ * This URL will be fetched on preview update events.
17
+ */
18
+ updatePreviewURL?: string;
19
+
20
+ /**
21
+ * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).
22
+ * This URL will be fetched on preview exit events.
23
+ */
24
+ exitPreviewURL?: string;
25
+
26
+ /** Children to render adjacent to the Prismic Toolbar. */
27
+ children?: ReactNode;
28
+ };
29
+
30
+ /**
31
+ * React component that sets up Prismic Previews using the Prismic Toolbar. When
32
+ * the Prismic Toolbar send events to the browser, such as on preview updates
33
+ * and exiting, this component will automatically refresh the page with the
34
+ * changes.
35
+ *
36
+ * This component can be wrapped around your app or added anywhere in your app's
37
+ * tree. It must be rendered on every page.
38
+ */
39
+ export function PrismicPreview(props: PrismicPreviewProps): JSX.Element {
40
+ const {
41
+ repositoryName,
42
+ updatePreviewURL = "/api/preview",
43
+ exitPreviewURL = "/api/exit-preview",
44
+ children,
45
+ } = props;
46
+
47
+ const router = useRouter();
48
+
49
+ const toolbarSrc = getToolbarSrc(repositoryName);
50
+
51
+ useEffect(() => {
52
+ const controller = new AbortController();
53
+
54
+ window.addEventListener("prismicPreviewUpdate", onUpdate, {
55
+ signal: controller.signal,
56
+ });
57
+ window.addEventListener("prismicPreviewEnd", onEnd, {
58
+ signal: controller.signal,
59
+ });
60
+
61
+ // Start the preview for preview share links. Previews from
62
+ // share links do not go to the `updatePreviewURL` like a normal
63
+ // preview.
64
+ //
65
+ // We check that the current URL is a descendant of the base
66
+ // path to prevent infinite refrehes.
67
+ if (
68
+ window.location.href.startsWith(
69
+ window.location.origin + router.basePath,
70
+ ) &&
71
+ getPreviewCookieRepositoryName() === repositoryName &&
72
+ !router.isPreview
73
+ ) {
74
+ start();
75
+ }
76
+
77
+ function onEnd(event: Event) {
78
+ event.preventDefault();
79
+ fetch(router.basePath + exitPreviewURL, { signal: controller.signal })
80
+ .then((res) => {
81
+ if (!res.ok) {
82
+ console.error(
83
+ `[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`,
84
+ );
85
+
86
+ return;
87
+ }
88
+
89
+ refresh();
90
+ })
91
+ .catch(() => {});
92
+ }
93
+
94
+ function onUpdate(event: Event) {
95
+ event.preventDefault();
96
+ start();
97
+ }
98
+
99
+ function start() {
100
+ // We check `opaqueredirect` because we don't care if
101
+ // the redirect was successful or not. As long as it
102
+ // redirects, we know the endpoint exists and at least
103
+ // attempted to set preview data.
104
+ fetch(router.basePath + updatePreviewURL, {
105
+ redirect: "manual",
106
+ signal: controller.signal,
107
+ })
108
+ .then((res) => {
109
+ if (res.type !== "opaqueredirect") {
110
+ console.error(
111
+ `[<PrismicPreview>] Failed to start or update the preview using "${updatePreviewURL}". Does it exist?`,
112
+ );
113
+
114
+ return;
115
+ }
116
+
117
+ refresh();
118
+ })
119
+ .catch(() => {});
120
+ }
121
+
122
+ function refresh() {
123
+ router.replace(router.asPath, undefined, { scroll: false });
124
+ }
125
+
126
+ return () => controller.abort();
127
+ }, [exitPreviewURL, updatePreviewURL, repositoryName, router]);
128
+
129
+ return (
130
+ <>
131
+ {children}
132
+ <Script src={toolbarSrc} strategy="lazyOnload" />
133
+ </>
134
+ );
135
+ }
136
+
137
+ function getPreviewCookieRepositoryName() {
138
+ const cookie = window.document.cookie
139
+ .split("; ")
140
+ .find((row) => row.startsWith(`${prismicCookie.preview}=`))
141
+ ?.split("=")[1];
142
+
143
+ return (decodeURIComponent(cookie ?? "").match(/"([^"]+)\.prismic\.io"/) ||
144
+ [])[1];
145
+ }
@@ -0,0 +1,62 @@
1
+ import type { PreviewData } from "next";
2
+ import type { Client } from "@prismicio/client";
3
+
4
+ import type { NextApiRequestLike } from "./types.js";
5
+
6
+ /**
7
+ * Configuration for `enableAutoPreviews`.
8
+ *
9
+ * @typeParam TPreviewData - Next.js preview data object.
10
+ */
11
+ export type EnableAutoPreviewsConfig = {
12
+ /** Prismic client with which automatic previews will be enabled. */
13
+ // `Pick` is used to use the smallest possible subset of
14
+ // `prismic.Client`. Doing this reduces the surface area for breaking
15
+ // type changes.
16
+ client: Pick<Client, "queryContentFromRef" | "enableAutoPreviewsFromReq">;
17
+
18
+ /**
19
+ * The `previewData` object provided in the `getStaticProps()` or
20
+ * `getServerSideProps()` context object.
21
+ */
22
+ previewData?: PreviewData;
23
+
24
+ /**
25
+ * The `req` object from a Next.js API route.
26
+ *
27
+ * @see Next.js API route docs: \<https://nextjs.org/docs/api-routes/introduction\>
28
+ */
29
+ req?: NextApiRequestLike;
30
+ };
31
+
32
+ /**
33
+ * Configures a Prismic client to automatically query draft content during a
34
+ * preview session. It either takes in a Next.js `getStaticProps` context object
35
+ * or a Next.js API endpoint request object.
36
+ *
37
+ * @param config - Configuration for the function.
38
+ */
39
+ export function enableAutoPreviews(config: EnableAutoPreviewsConfig): void {
40
+ if ("previewData" in config && config.previewData) {
41
+ // Assume we are in `getStaticProps()` or
42
+ // `getServerSideProps()` with active Preview Mode.
43
+
44
+ if (isPrismicPreviewData(config.previewData)) {
45
+ config.client.queryContentFromRef(config.previewData.ref);
46
+ }
47
+
48
+ return;
49
+ }
50
+
51
+ if ("req" in config && config.req) {
52
+ // Assume we are in an API Route.
53
+
54
+ config.client.enableAutoPreviewsFromReq(config.req);
55
+
56
+ return;
57
+ }
58
+ }
59
+
60
+ function isPrismicPreviewData(input: unknown): input is { ref: string } {
61
+ return typeof input === "object" && input !== null && "ref" in input;
62
+ }
@@ -0,0 +1,45 @@
1
+ import type { NextApiRequestLike, NextApiResponseLike } from "./types.js";
2
+
3
+ /** Configuration for `exitPreview()`. */
4
+ export type ExitPreviewAPIRouteConfig = {
5
+ /**
6
+ * The `req` object from a Next.js API route.
7
+ *
8
+ * @see Next.js API route docs: \<https://nextjs.org/docs/api-routes/introduction\>
9
+ */
10
+ req?: NextApiRequestLike;
11
+
12
+ /**
13
+ * The `res` object from a Next.js API route.
14
+ *
15
+ * @see Next.js API route docs: \<https://nextjs.org/docs/api-routes/introduction\>
16
+ */
17
+ res: NextApiResponseLike;
18
+ };
19
+
20
+ /**
21
+ * Ends a Prismic preview session within a Next.js app. This function should be
22
+ * used in an API route.
23
+ *
24
+ * @example
25
+ *
26
+ * ```typescript
27
+ * // src/pages/api/exit-preview.js
28
+ *
29
+ * import { exitPreview } from "@prismicio/next";
30
+ *
31
+ * export default function handler(_req, res) {
32
+ * return exitPreview({ res });
33
+ * }
34
+ * ```
35
+ */
36
+ export function exitPreview(config: ExitPreviewAPIRouteConfig): void {
37
+ config.res.clearPreviewData();
38
+
39
+ // `Cache-Control` header is used to prevent CDN-level caching.
40
+ config.res.setHeader("Cache-Control", "no-store");
41
+
42
+ config.res.json({ success: true });
43
+
44
+ return;
45
+ }
@@ -0,0 +1,27 @@
1
+ export { PrismicNextLink } from "../PrismicNextLink.js";
2
+ export { type PrismicNextLinkProps } from "../PrismicNextLink.js";
3
+
4
+ export { PrismicNextImage } from "../PrismicNextImage.js";
5
+ export { type PrismicNextImageProps } from "../PrismicNextImage.js";
6
+
7
+ export { imgixLoader } from "../imgixLoader.js";
8
+
9
+ export { PrismicPreview } from "./PrismicPreview.js";
10
+ export type { PrismicPreviewProps } from "./PrismicPreview.js";
11
+
12
+ export { enableAutoPreviews } from "./enableAutoPreviews.js";
13
+ export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews.js";
14
+
15
+ export { redirectToPreviewURL } from "./redirectToPreviewURL.js";
16
+ export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL.js";
17
+
18
+ export { exitPreview } from "./exitPreview.js";
19
+ export type { ExitPreviewAPIRouteConfig } from "./exitPreview.js";
20
+
21
+ export { setPreviewData } from "./setPreviewData.js";
22
+ export type { SetPreviewDataConfig } from "./setPreviewData.js";
23
+
24
+ export type { CreateClientConfig } from "./types.js";
25
+
26
+ export { createLocaleRedirect } from "../createLocaleRedirect.js";
27
+ export type { CreateLocaleRedirectConfig } from "../createLocaleRedirect.js";
@@ -0,0 +1,77 @@
1
+ import type { LinkResolverFunction, Client } from "@prismicio/client";
2
+
3
+ import type { NextApiRequestLike, NextApiResponseLike } from "./types.js";
4
+
5
+ export type RedirectToPreviewURLConfig = {
6
+ /** The Prismic client configured for the preview session's repository. */
7
+ // `Pick` is used to use the smallest possible subset of
8
+ // `prismic.Client`. Doing this reduces the surface area for breaking
9
+ // type changes.
10
+ client: Pick<Client, "resolvePreviewURL">;
11
+
12
+ /**
13
+ * The `req` object from a Next.js API route.
14
+ *
15
+ * @see Next.js API route docs: \<https://nextjs.org/docs/pages/building-your-application/routing/api-routes\>
16
+ */
17
+ req: NextApiRequestLike;
18
+
19
+ /**
20
+ * The `res` object from a Next.js API route.
21
+ *
22
+ * @see Next.js API route docs: \<https://nextjs.org/docs/pages/building-your-application/routing/api-routes\>
23
+ */
24
+ res: NextApiResponseLike;
25
+
26
+ /**
27
+ * A Link Resolver used to resolve the previewed document's URL.
28
+ *
29
+ * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
30
+ */
31
+ linkResolver?: LinkResolverFunction;
32
+
33
+ /**
34
+ * The default redirect URL if a URL cannot be determined for the previewed
35
+ * document.
36
+ *
37
+ * **Note**: If you `next.config.js` file contains a `basePath`, the
38
+ * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
39
+ * property using the `basePath` option.
40
+ */
41
+ defaultURL?: string;
42
+
43
+ /**
44
+ * The `basePath` for the Next.js app as it is defined in `next.config.js`.
45
+ * This option can be omitted if the app does not have a `basePath`.
46
+ *
47
+ * @remarks
48
+ * The Router Handler or API route is unable to detect the app's `basePath`
49
+ * automatically. It must be provided to `redirectToPreviewURL()` manually.
50
+ */
51
+ basePath?: string;
52
+ };
53
+
54
+ export async function redirectToPreviewURL(
55
+ config: RedirectToPreviewURLConfig,
56
+ ): Promise<void> {
57
+ const {
58
+ client,
59
+ req,
60
+ res,
61
+ linkResolver,
62
+ defaultURL = "/",
63
+ basePath = "",
64
+ } = config;
65
+
66
+ const previewToken = req.query.token?.toString();
67
+
68
+ const previewURL = await client.resolvePreviewURL({
69
+ linkResolver,
70
+ defaultURL,
71
+ previewToken,
72
+ });
73
+
74
+ res.redirect(basePath + previewURL);
75
+
76
+ return;
77
+ }
@@ -1,10 +1,8 @@
1
- import * as prismic from "@prismicio/client";
1
+ import { cookie } from "@prismicio/client";
2
2
 
3
- import { NextApiRequestLike, NextApiResponseLike } from "./types";
3
+ import type { NextApiRequestLike, NextApiResponseLike } from "./types.js";
4
4
 
5
- /**
6
- * Configuration for `setPreviewData`.
7
- */
5
+ /** Configuration for `setPreviewData`. */
8
6
  export type SetPreviewDataConfig = {
9
7
  /**
10
8
  * The `req` object from a Next.js API route.
@@ -21,13 +19,9 @@ export type SetPreviewDataConfig = {
21
19
  res: NextApiResponseLike;
22
20
  };
23
21
 
24
- /**
25
- * **Only use this function in the Pages Directory (/pages).**
26
- *
27
- * Set Prismic preview data for Next.js's Preview Mode.
28
- */
22
+ /** Set Prismic preview data for Next.js's Preview Mode. */
29
23
  export function setPreviewData({ req, res }: SetPreviewDataConfig): void {
30
- const ref = req.query.token || req.cookies[prismic.cookie.preview];
24
+ const ref = req.query.token || req.cookies[cookie.preview];
31
25
 
32
26
  if (ref) {
33
27
  res.setPreviewData({ ref });
@@ -0,0 +1,36 @@
1
+ import type { ClientConfig } from "@prismicio/client";
2
+
3
+ import { EnableAutoPreviewsConfig } from "./enableAutoPreviews.js";
4
+
5
+ /**
6
+ * Configuration for creating a Prismic client with automatic preview support in
7
+ * Next.js apps.
8
+ */
9
+ export type CreateClientConfig = ClientConfig &
10
+ Pick<EnableAutoPreviewsConfig, "previewData" | "req">;
11
+
12
+ /**
13
+ * The minimal set of properties needed from `next`'s `NextApiRequest` type.
14
+ *
15
+ * This request type is only compatible with API routes defined in the `pages`
16
+ * directory.
17
+ */
18
+ export type NextApiRequestLike = {
19
+ query: Partial<Record<string, string | string[]>>;
20
+ cookies: Partial<Record<string, string>>;
21
+ };
22
+
23
+ /**
24
+ * The minimal set of properties needed from `next`'s `NextApiResponse` type.
25
+ *
26
+ * This request type is only compatible with API routes defined in the `pages`
27
+ * directory.
28
+ */
29
+ export type NextApiResponseLike = {
30
+ redirect(url: string): NextApiResponseLike;
31
+ clearPreviewData(): NextApiResponseLike;
32
+ setHeader(name: string, value: string | string[]): NextApiResponseLike;
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ json(body: any): void;
35
+ setPreviewData(data: object | string): NextApiResponseLike;
36
+ };
@@ -1,31 +1,32 @@
1
1
  import { redirect } from "next/navigation";
2
- import { cookies, draftMode } from "next/headers";
3
- import * as prismic from "@prismicio/client";
4
-
5
2
  import {
6
- NextApiRequestLike,
7
- NextApiResponseLike,
8
- NextRequestLike,
9
- } from "./types";
3
+ cookie as prismicCookie,
4
+ type Client,
5
+ type LinkResolverFunction,
6
+ } from "@prismicio/client";
10
7
 
11
- type RedirectToPreviewURLConfigBase = {
12
- /**
13
- * The Prismic client configured for the preview session's repository.
14
- */
8
+ import { NextRequestLike } from "./types.js";
9
+
10
+ export type RedirectToPreviewURLConfig = {
11
+ /** The Prismic client configured for the preview session's repository. */
15
12
  // `Pick` is used to use the smallest possible subset of
16
13
  // `prismic.Client`. Doing this reduces the surface area for breaking
17
14
  // type changes.
18
- client: Pick<
19
- prismic.Client,
20
- "enableAutoPreviewsFromReq" | "resolvePreviewURL"
21
- >;
15
+ client: Pick<Client, "resolvePreviewURL">;
16
+
17
+ /**
18
+ * The `request` object from a Next.js Route Handler.
19
+ *
20
+ * @see Next.js Route Handler docs: \<https://nextjs.org/docs/app/building-your-application/routing/route-handlers\>
21
+ */
22
+ request: NextRequestLike;
22
23
 
23
24
  /**
24
25
  * A Link Resolver used to resolve the previewed document's URL.
25
26
  *
26
27
  * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
27
28
  */
28
- linkResolver?: prismic.LinkResolverFunction;
29
+ linkResolver?: LinkResolverFunction;
29
30
 
30
31
  /**
31
32
  * The default redirect URL if a URL cannot be determined for the previewed
@@ -36,91 +37,39 @@ type RedirectToPreviewURLConfigBase = {
36
37
  * property using the `basePath` option.
37
38
  */
38
39
  defaultURL?: string;
39
-
40
- /**
41
- * The `basePath` for the Next.js app as it is defined in `next.config.js`.
42
- * This option can be omitted if the app does not have a `basePath`.
43
- *
44
- * @remarks
45
- * The Router Handler or API route is unable to detect the app's `basePath`
46
- * automatically. It must be provided to `redirectToPreviewURL()` manually.
47
- */
48
- basePath?: string;
49
40
  };
50
41
 
51
- export type RedirectToPreviewURLRouteHandlerConfig =
52
- RedirectToPreviewURLConfigBase & {
53
- /**
54
- * The `request` object from a Next.js Route Handler.
55
- *
56
- * @see Next.js Route Handler docs: \<https://nextjs.org/docs/app/building-your-application/routing/route-handlers\>
57
- */
58
- request: NextRequestLike;
59
- };
60
-
61
- export type RedirectToPreviewURLAPIEndpointConfig =
62
- RedirectToPreviewURLConfigBase & {
63
- /**
64
- * The `req` object from a Next.js API route.
65
- *
66
- * @see Next.js API route docs: \<https://nextjs.org/docs/pages/building-your-application/routing/api-routes\>
67
- */
68
- req: NextApiRequestLike;
69
-
70
- /**
71
- * The `res` object from a Next.js API route.
72
- *
73
- * @see Next.js API route docs: \<https://nextjs.org/docs/pages/building-your-application/routing/api-routes\>
74
- */
75
- res: NextApiResponseLike;
76
- };
77
-
78
- export type RedirectToPreviewURLConfig =
79
- | RedirectToPreviewURLRouteHandlerConfig
80
- | RedirectToPreviewURLAPIEndpointConfig;
81
-
82
- export async function redirectToPreviewURL(
83
- config: RedirectToPreviewURLRouteHandlerConfig,
84
- ): Promise<never>;
85
- export async function redirectToPreviewURL(
86
- config: RedirectToPreviewURLAPIEndpointConfig,
87
- ): Promise<void>;
88
42
  export async function redirectToPreviewURL(
89
43
  config: RedirectToPreviewURLConfig,
90
- ): Promise<never | void> {
91
- const basePath = config.basePath || "";
92
- const request = "request" in config ? config.request : config.req;
93
-
94
- config.client.enableAutoPreviewsFromReq(request);
44
+ ): Promise<never> {
45
+ const { client, request, linkResolver, defaultURL = "/" } = config;
46
+
47
+ // Need this to avoid the following Next.js build-time error:
48
+ // You're importing a component that needs next/headers. That only works
49
+ // in a Server Component which is not supported in the pages/ directory.
50
+ const { cookies, draftMode } = await import("next/headers");
51
+
52
+ const documentID =
53
+ request.nextUrl.searchParams.get("documentId") ?? undefined;
54
+
55
+ // Set the initial preview cookie. Setting the cookie here is necessary
56
+ // to support unpublished previews. Without setting it here, the page
57
+ // will try to render without the preview cookie, leading to a
58
+ // PrismicNotFound error.
59
+ const previewToken = request.nextUrl.searchParams.get("token") ?? undefined;
60
+ if (previewToken) {
61
+ const cookieJar = await cookies();
62
+ cookieJar.set(prismicCookie.preview, previewToken);
63
+ }
95
64
 
96
- const previewUrl = await config.client.resolvePreviewURL({
97
- linkResolver: config.linkResolver,
98
- defaultURL: config.defaultURL || "/",
65
+ const previewURL = await client.resolvePreviewURL({
66
+ documentID,
67
+ previewToken,
68
+ defaultURL,
69
+ linkResolver,
99
70
  });
100
71
 
101
- if ("nextUrl" in request) {
102
- (await draftMode()).enable();
103
-
104
- // Set the initial preview cookie, if available.
105
- // Setting the cookie here is necessary to support unpublished
106
- // previews. Without setting it here, the page will try to
107
- // render without the preview cookie, leading to a
108
- // PrismicNotFound error.
109
- const previewCookie = request.nextUrl.searchParams.get("token");
110
- if (previewCookie) {
111
- (await cookies()).set(prismic.cookie.preview, previewCookie);
112
- }
72
+ (await draftMode()).enable();
113
73
 
114
- redirect(basePath + previewUrl);
115
- } else {
116
- if (!("res" in config)) {
117
- throw new Error(
118
- "[redirectToPreviewURL] The `res` object from the API route must be provided to `redirectToPreviewURL()`.",
119
- );
120
- }
121
-
122
- config.res.redirect(basePath + previewUrl);
123
-
124
- return;
125
- }
74
+ redirect(previewURL);
126
75
  }
package/src/types.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { PreviewData } from "next";
2
1
  import type { ClientConfig } from "@prismicio/client";
3
2
 
4
3
  // Add Next.js-specific fetchOptions to `@prismicio/client`.
@@ -8,35 +7,8 @@ declare module "@prismicio/client" {
8
7
  }
9
8
  }
10
9
 
11
- /**
12
- * Prismic data saved in Next.js Preview Mode's object.
13
- */
14
- export type PrismicPreviewData = {
15
- ref: string;
16
- };
17
-
18
- /**
19
- * Configuration for creating a Prismic client with automatic preview support in
20
- * Next.js apps.
21
- */
22
- export type CreateClientConfig = ClientConfig & {
23
- /**
24
- * **Only used in the Pages Directory (/pages).**
25
- *
26
- * The `previewData` object provided in the `getStaticProps()` or
27
- * `getServerSideProps()` context object.
28
- */
29
- previewData?: PreviewData;
30
-
31
- /**
32
- * **Only used in the Pages Directory (/pages).**
33
- *
34
- * The `req` object from a Next.js API route.
35
- *
36
- * @see Next.js API route docs: \<https://nextjs.org/docs/api-routes/introduction\>
37
- */
38
- req?: NextApiRequestLike;
39
- };
10
+ /** @deprecated Use `@prismicio/client`'s `ClientConfig`. */
11
+ export type CreateClientConfig = ClientConfig;
40
12
 
41
13
  /**
42
14
  * The minimal set of properties needed from `next`'s `NextRequest` type.
@@ -56,29 +28,3 @@ export type NextRequestLike = {
56
28
  };
57
29
  };
58
30
  };
59
-
60
- /**
61
- * The minimal set of properties needed from `next`'s `NextApiRequest` type.
62
- *
63
- * This request type is only compatible with API routes defined in the `pages`
64
- * directory.
65
- */
66
- export type NextApiRequestLike = {
67
- query: Partial<Record<string, string | string[]>>;
68
- cookies: Partial<Record<string, string>>;
69
- };
70
-
71
- /**
72
- * The minimal set of properties needed from `next`'s `NextApiResponse` type.
73
- *
74
- * This request type is only compatible with API routes defined in the `pages`
75
- * directory.
76
- */
77
- export type NextApiResponseLike = {
78
- redirect(url: string): NextApiResponseLike;
79
- clearPreviewData(): NextApiResponseLike;
80
- setHeader(name: string, value: string | string[]): NextApiResponseLike;
81
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
- json(body: any): void;
83
- setPreviewData(data: object | string): NextApiResponseLike;
84
- };