@prismicio/next 0.1.1 → 0.1.4-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.
@@ -1,9 +1,9 @@
1
- import React, { useEffect } from "react";
1
+ import * as React from "react";
2
2
  import { PrismicToolbar } from "@prismicio/react";
3
3
  import { useRouter } from "next/router";
4
4
 
5
- import { getCookie } from "../lib/getCookie";
6
- import { extractPreviewRefRepositoryName } from "../lib/extractPreviewRefRepositoryName";
5
+ import { getPrismicPreviewCookie } from "./lib/getPrismicPreviewCookie";
6
+ import { getPreviewCookieRepositoryName } from "./lib/getPreviewCookieRepositoryName";
7
7
 
8
8
  /**
9
9
  * Props for `<PrismicPreview>`.
@@ -18,33 +18,28 @@ export type PrismicPreviewProps = {
18
18
  /**
19
19
  * The URL of your app's Prismic preview endpoint (default: `/api/preview`).
20
20
  * This URL will be fetched on preview update events.
21
+ *
22
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
23
+ * automatically included.
21
24
  */
22
25
  updatePreviewURL?: string;
23
26
 
24
27
  /**
25
28
  * The URL of your app's exit preview endpoint (default: `/api/exit-preview`).
26
29
  * This URL will be fetched on preview exit events.
30
+ *
31
+ * **Note**: If your `next.config.js` file contains a `basePath`, it is
32
+ * automatically included.
27
33
  */
28
34
  exitPreviewURL?: string;
29
35
 
36
+ /**
37
+ * Children to render adjacent to the Prismic Toolbar. The Prismic Toolbar
38
+ * will be rendered last.
39
+ */
30
40
  children?: React.ReactNode;
31
41
  };
32
42
 
33
- /**
34
- * Determines if an Event object came from the Prismic Toolbar.
35
- *
36
- * @param event - Event to check.
37
- *
38
- * @returns `true` if `event` came from the Prismic Toolbar, `false` otherwise.
39
- */
40
- const isPrismicUpdateToolbarEvent = (
41
- event: Event,
42
- ): event is CustomEvent<{ ref: string }> => {
43
- return (
44
- "detail" in event && typeof (event as CustomEvent).detail.ref === "string"
45
- );
46
- };
47
-
48
43
  /**
49
44
  * React component that sets up Prismic Previews using the Prismic Toolbar. When
50
45
  * the Prismic Toolbar send events to the browser, such as on preview updates
@@ -62,31 +57,31 @@ export function PrismicPreview({
62
57
  }: PrismicPreviewProps): JSX.Element {
63
58
  const router = useRouter();
64
59
 
65
- useEffect(() => {
66
- const previewRefRepositoryName = extractPreviewRefRepositoryName(
67
- getCookie("io.prismic.preview", globalThis.document.cookie) as string,
68
- );
69
-
70
- const startPreviewIfLoadedFromSharedLink = async () => {
71
- if (previewRefRepositoryName === repositoryName && !router.isPreview) {
72
- await fetch(updatePreviewURL);
73
- window.location.reload();
60
+ const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
61
+ const resolvedExitPreviewURL = router.basePath + exitPreviewURL;
62
+
63
+ React.useEffect(() => {
64
+ /**
65
+ * Starts Preview Mode and refreshes the page's props.
66
+ */
67
+ const startPreviewMode = async () => {
68
+ // Start Next.js Preview Mode via the given preview API endpoint.
69
+ const res = await globalThis.fetch(resolvedUpdatePreviewURL);
70
+
71
+ if (res.ok) {
72
+ globalThis.location.reload();
73
+ } else {
74
+ console.error(
75
+ `[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`,
76
+ );
74
77
  }
75
78
  };
76
79
 
77
- startPreviewIfLoadedFromSharedLink();
78
-
79
80
  const handlePrismicPreviewUpdate = async (event: Event) => {
80
- if (isPrismicUpdateToolbarEvent(event)) {
81
- // Prevent the toolbar from reloading the page.
82
- event.preventDefault();
83
-
84
- // Start Next.js Preview Mode via the given preview API endpoint.
85
- await fetch(updatePreviewURL);
81
+ // Prevent the toolbar from reloading the page.
82
+ event.preventDefault();
86
83
 
87
- // Reload the page with an active Preview Mode.
88
- window.location.reload();
89
- }
84
+ await startPreviewMode();
90
85
  };
91
86
 
92
87
  const handlePrismicPreviewEnd = async (event: Event) => {
@@ -94,40 +89,80 @@ export function PrismicPreview({
94
89
  event.preventDefault();
95
90
 
96
91
  // Exit Next.js Preview Mode via the given preview API endpoint.
97
- await fetch(exitPreviewURL);
92
+ const res = await globalThis.fetch(resolvedExitPreviewURL);
98
93
 
99
- // Reload the page with an active Preview Mode.
100
- window.location.reload();
94
+ if (res.ok) {
95
+ globalThis.location.reload();
96
+ } else {
97
+ console.error(
98
+ `[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`,
99
+ );
100
+ }
101
101
  };
102
102
 
103
- // Register Prismic Toolbar event handlers.
104
- if (window) {
103
+ if (router.isPreview) {
104
+ // Register Prismic Toolbar event handlers.
105
105
  window.addEventListener(
106
106
  "prismicPreviewUpdate",
107
107
  handlePrismicPreviewUpdate,
108
108
  );
109
109
  window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
110
+ } else {
111
+ const prismicPreviewCookie = getPrismicPreviewCookie(
112
+ globalThis.document.cookie,
113
+ );
114
+
115
+ if (prismicPreviewCookie) {
116
+ // If a Prismic preview cookie is present, but Next.js Preview
117
+ // Mode is not active, we must activate Preview Mode manually.
118
+ //
119
+ // This will happen when a visitor accesses the page using a
120
+ // Prismic preview share link.
121
+
122
+ /**
123
+ * Determines if the current location is a descendant of the app's base path.
124
+ *
125
+ * This is used to prevent infinite refrehes; when
126
+ * `isDescendantOfBasePath` is `false`, `router.isPreview` is also `false`.
127
+ *
128
+ * If the app does not have a base path, this should always be `true`.
129
+ */
130
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(
131
+ window.location.origin + router.basePath,
132
+ );
133
+
134
+ const prismicPreviewCookieRepositoryName =
135
+ getPreviewCookieRepositoryName(prismicPreviewCookie);
136
+
137
+ if (
138
+ locationIsDescendantOfBasePath &&
139
+ prismicPreviewCookieRepositoryName === repositoryName
140
+ ) {
141
+ startPreviewMode();
142
+ }
143
+ }
110
144
  }
111
145
 
112
146
  // On cleanup, unregister Prismic Toolbar event handlers.
113
147
  return () => {
114
- if (window) {
115
- window.removeEventListener(
116
- "prismicPreviewUpdate",
117
- handlePrismicPreviewUpdate,
118
- );
119
- window.removeEventListener(
120
- "prismicPreviewEnd",
121
- handlePrismicPreviewEnd,
122
- );
123
- }
148
+ window.removeEventListener(
149
+ "prismicPreviewUpdate",
150
+ handlePrismicPreviewUpdate,
151
+ );
152
+ window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
124
153
  };
125
- }, []);
154
+ }, [
155
+ repositoryName,
156
+ resolvedExitPreviewURL,
157
+ resolvedUpdatePreviewURL,
158
+ router.isPreview,
159
+ router.basePath,
160
+ ]);
126
161
 
127
162
  return (
128
163
  <>
129
- <PrismicToolbar repositoryName={repositoryName} />
130
164
  {children}
165
+ <PrismicToolbar repositoryName={repositoryName} />
131
166
  </>
132
167
  );
133
168
  }
@@ -60,19 +60,17 @@ export type EnableAutoPreviewsConfig<
60
60
  export const enableAutoPreviews = <TPreviewData extends PreviewData>(
61
61
  config: EnableAutoPreviewsConfig<TPreviewData>,
62
62
  ): void => {
63
- /**
64
- * If preview data is being passed from Next Context then use queryContentFromRef
65
- */
66
63
  if ("previewData" in config && config.previewData) {
64
+ // If preview data is being passed from Next Context then use queryContentFromRef
65
+
67
66
  const { previewData } = config;
68
67
 
69
68
  if (isPrismicNextPreviewData(previewData) && previewData.ref) {
70
69
  config.client.queryContentFromRef(previewData.ref);
71
70
  }
72
- /**
73
- * If the req object is passed then use enableAutoPreviewsFromReq
74
- */
75
71
  } else if ("req" in config && config.req) {
72
+ // If the req object is passed then use enableAutoPreviewsFromReq
73
+
76
74
  config.client.enableAutoPreviewsFromReq(config.req);
77
75
  }
78
76
  };
@@ -1,4 +1,4 @@
1
- import { NextApiResponse, NextApiRequest } from "next";
1
+ import type { NextApiResponse, NextApiRequest } from "next";
2
2
 
3
3
  /**
4
4
  * Configuration for `exitPreview`.
@@ -10,10 +10,18 @@ export type ExitPreviewConfig = {
10
10
  *
11
11
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
12
12
  */
13
+ // `req` is no longer used in `exitPreview()`. It previously would
14
+ // redirect the user to the referring URL, but it no longer has that
15
+ // behavior.
16
+ //
17
+ // `req` is retained as a parameter to make setting up an exit preview
18
+ // API route easier (this eliminates the awkward need to handle an
19
+ // unused `req` param).
20
+ //
21
+ // It is also retained in case it is needed in the future, such as
22
+ // reading headers or metadata about the request.
13
23
  req: {
14
- headers: {
15
- referer?: NextApiRequest["headers"]["referer"];
16
- };
24
+ headers: NextApiRequest["headers"];
17
25
  };
18
26
 
19
27
  /**
@@ -24,31 +32,24 @@ export type ExitPreviewConfig = {
24
32
  */
25
33
  res: {
26
34
  clearPreviewData: NextApiResponse["clearPreviewData"];
27
- redirect: NextApiResponse["redirect"];
35
+ status: NextApiResponse["status"];
36
+ json: NextApiResponse["json"];
28
37
  };
38
+
39
+ /**
40
+ * @deprecated - This property is no longer used. It can be deleted safely.
41
+ */
42
+ exitPreviewURL?: string;
29
43
  };
30
44
 
31
45
  /**
32
46
  * Exits Next.js's Preview Mode from within a Next.js API route.
33
- *
34
- * If the user was sent to the endpoint from a page, the user will be redirected
35
- * back to that page after exiting Preview Mode.
36
47
  */
37
48
  export function exitPreview(config: ExitPreviewConfig): void {
38
- const { req } = config;
39
- // Exit the current user from "Preview Mode". This function accepts no args.
49
+ // Exit the current user from Preview Mode.
40
50
  config.res.clearPreviewData();
41
51
 
42
- if (req.headers.referer) {
43
- const url = new URL(req.headers.referer);
44
-
45
- if (url.pathname !== "/api/exit-preview") {
46
- // Redirect the user to the referrer page.
47
- config.res.redirect(req.headers.referer);
48
-
49
- return;
50
- }
51
- }
52
-
53
- config.res.redirect("/");
52
+ // 205 status is used to prevent CDN-level caching. The default 200
53
+ // status code is typically treated as non-changing and cacheable.
54
+ config.res.status(205).json({ success: true });
54
55
  }
package/src/index.ts CHANGED
@@ -1,10 +1,19 @@
1
- export type { SetPreviewDataConfig } from "./setPreviewData";
2
- export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
3
- export type { ExitPreviewConfig as ExitPreviewParams } from "./exitPreview";
4
- export type { PrismicPreviewProps } from "./PrismicPreview";
5
1
  export { setPreviewData } from "./setPreviewData";
2
+ export type { SetPreviewDataConfig } from "./setPreviewData";
3
+
6
4
  export { exitPreview } from "./exitPreview";
5
+ export type { ExitPreviewConfig } from "./exitPreview";
6
+
7
7
  export { PrismicPreview } from "./PrismicPreview";
8
+ export type { PrismicPreviewProps } from "./PrismicPreview";
9
+
8
10
  export { enableAutoPreviews } from "./enableAutoPreviews";
11
+ export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
12
+
9
13
  export { redirectToPreviewURL } from "./redirectToPreviewURL";
10
- export type { CreateClientConfig, PreviewConfig } from "./types";
14
+ export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL";
15
+
16
+ export { PrismicNextImage } from "./PrismicNextImage";
17
+ export type { PrismicNextImageProps } from "./PrismicNextImage";
18
+
19
+ export type { CreateClientConfig } from "./types";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `true` if in the production environment, `false` otherwise.
3
+ *
4
+ * This boolean can be used to perform actions only in development environments,
5
+ * such as logging.
6
+ */
7
+ export const __PRODUCTION__ = process.env.NODE_ENV === "production";
@@ -0,0 +1,20 @@
1
+ import { version } from "../../package.json";
2
+
3
+ /**
4
+ * Returns a `prismic.dev/msg` URL for a given message slug.
5
+ *
6
+ * @example
7
+ *
8
+ * ```ts
9
+ * devMsg("missing-param");
10
+ * // => "https://prismic.dev/msg/next/v1.2.3/missing-param.md"
11
+ * ```
12
+ *
13
+ * @param slug - Slug for the message. This corresponds to a Markdown file in
14
+ * the Git repository's `/messages` directory.
15
+ *
16
+ * @returns The `prismic.dev/msg` URL for the given slug.
17
+ */
18
+ export const devMsg = (slug: string) => {
19
+ return `https://prismic.dev/msg/next/v${version}/${slug}`;
20
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Extracts preview reference repo name from stringified Prismic preview cookie
3
+ *
4
+ * @param previewCookie - The Prismic preview cookie.
5
+ *
6
+ * @returns The repository name for the Prismic preview cookie. If the cookie
7
+ * represents an inactive preview session, `undefined` will be returned.
8
+ */
9
+ export const getPreviewCookieRepositoryName = (
10
+ previewCookie: string,
11
+ ): string | undefined => {
12
+ return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) ||
13
+ [])[1];
14
+ };
@@ -0,0 +1,32 @@
1
+ import * as prismic from "@prismicio/client";
2
+
3
+ const readValue = (value: string): string => {
4
+ return value.replace(/%3B/g, ";");
5
+ };
6
+
7
+ /**
8
+ * Returns the value of a cookie from a given cookie store.
9
+ *
10
+ * @param cookieJar - The stringified cookie store from which to read the cookie.
11
+ *
12
+ * @returns The value of the cookie, if it exists.
13
+ */
14
+ export const getPrismicPreviewCookie = (
15
+ cookieJar: string,
16
+ ): string | undefined => {
17
+ const cookies = cookieJar.split("; ");
18
+
19
+ let value: string | undefined;
20
+
21
+ for (const cookie of cookies) {
22
+ const parts = cookie.split("=");
23
+ const name = readValue(parts[0]).replace(/%3D/g, "=");
24
+
25
+ if (name === prismic.cookie.preview) {
26
+ value = readValue(parts.slice(1).join("="));
27
+ continue;
28
+ }
29
+ }
30
+
31
+ return value;
32
+ };
@@ -1,5 +1,6 @@
1
- import { NextApiRequest } from "next";
2
- import { PreviewConfig } from "./";
1
+ import type { Client } from "@prismicio/client";
2
+ import type { NextApiRequest, NextApiResponse } from "next";
3
+ import type { LinkResolverFunction } from "@prismicio/helpers";
3
4
 
4
5
  type PrismicNextQuery = {
5
6
  documentId: string;
@@ -16,33 +17,94 @@ type PrismicNextQuery = {
16
17
  */
17
18
  const isPrismicNextQuery = (
18
19
  query: NextApiRequest["query"],
19
- ): query is PrismicNextQuery =>
20
- typeof query.documentId === "string" && typeof query.token === "string";
20
+ ): query is PrismicNextQuery => {
21
+ return (
22
+ typeof query.documentId === "string" && typeof query.token === "string"
23
+ );
24
+ };
25
+
26
+ /**
27
+ * Preview config for enabling previews with redirectToPreviewURL
28
+ */
29
+ export type RedirectToPreviewURLConfig<
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ TLinkResolverFunction extends LinkResolverFunction<any> = LinkResolverFunction,
32
+ > = {
33
+ /**
34
+ * The `req` object from a Next.js API route. This is given as a parameter to
35
+ * the API route.
36
+ *
37
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
38
+ */
39
+ req: {
40
+ query: NextApiRequest["query"];
41
+ };
42
+
43
+ /**
44
+ * The `res` object from a Next.js API route. This is given as a parameter to
45
+ * the API route.
46
+ *
47
+ * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
48
+ */
49
+ res: {
50
+ redirect: NextApiResponse["redirect"];
51
+ };
52
+
53
+ /**
54
+ * The Prismic client configured for the preview session's repository.
55
+ */
56
+ client: Client;
57
+
58
+ /**
59
+ * A Link Resolver used to resolve the previewed document's URL.
60
+ *
61
+ * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
62
+ */
63
+ linkResolver?: TLinkResolverFunction;
64
+
65
+ /**
66
+ * The default redirect URL if a URL cannot be determined for the previewed document.
67
+ *
68
+ * **Note**: If you `next.config.js` file contains a `basePath`, the
69
+ * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
70
+ * property using the `basePath` option.
71
+ */
72
+ defaultURL?: string;
73
+
74
+ /**
75
+ * The `basePath` for the Next.js app as it is defined in `next.config.js`.
76
+ * This option can be omitted if the app does not have a `basePath`.
77
+ *
78
+ * @remarks
79
+ * The API route is unable to detect the app's `basePath` automatically. It
80
+ * must be provided to `redirectToPreviewURL()` manually.
81
+ */
82
+ basePath?: string;
83
+ };
21
84
 
22
85
  /**
23
86
  * Redirects a user to the URL of a previewed Prismic document from within a
24
87
  * Next.js API route.
25
88
  */
26
- export async function redirectToPreviewURL({
27
- req,
28
- res,
29
- client,
30
- linkResolver,
31
- defaultURL = "/",
32
- }: PreviewConfig): Promise<void> {
33
- if (isPrismicNextQuery(req.query)) {
34
- const { documentId, token } = req.query;
35
- const previewUrl = await client.resolvePreviewURL({
36
- linkResolver,
89
+ export async function redirectToPreviewURL<
90
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
+ TLinkResolverFunction extends LinkResolverFunction<any>,
92
+ >(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void> {
93
+ const defaultURL = config.defaultURL || "/";
94
+ const basePath = config.basePath || "";
95
+
96
+ if (isPrismicNextQuery(config.req.query)) {
97
+ const previewUrl = await config.client.resolvePreviewURL({
98
+ linkResolver: config.linkResolver,
37
99
  defaultURL,
38
- documentID: documentId,
39
- previewToken: token,
100
+ documentID: config.req.query.documentId,
101
+ previewToken: config.req.query.token,
40
102
  });
41
103
 
42
- res.redirect(previewUrl);
104
+ config.res.redirect(basePath + previewUrl);
43
105
 
44
106
  return;
45
107
  }
46
108
 
47
- res.redirect(defaultURL);
109
+ config.res.redirect(basePath + defaultURL);
48
110
  }
@@ -30,10 +30,7 @@ export type SetPreviewDataConfig = {
30
30
  /**
31
31
  * Set Prismic preview data for Next.js's Preview Mode.
32
32
  */
33
- export async function setPreviewData({
34
- req,
35
- res,
36
- }: SetPreviewDataConfig): Promise<void> {
33
+ export function setPreviewData({ req, res }: SetPreviewDataConfig): void {
37
34
  const ref = req.query.token || req.cookies[prismic.cookie.preview];
38
35
 
39
36
  if (ref) {
package/src/types.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { PreviewData, NextApiRequest, NextApiResponse } from "next";
2
- import { LinkResolverFunction } from "@prismicio/helpers";
3
- import { Client } from "@prismicio/client";
1
+ import type { PreviewData, NextApiRequest } from "next";
2
+ import type { ClientConfig } from "@prismicio/client";
4
3
 
5
4
  /**
6
5
  * Configuration for creating a Prismic client with automatic preview support in
@@ -21,46 +20,4 @@ export type CreateClientConfig = {
21
20
  * Pass a `req` object when using in a Next.js API endpoint.
22
21
  */
23
22
  req?: NextApiRequest;
24
- };
25
-
26
- /**
27
- * Preview config for enabling previews with redirectToPreviewURL
28
- */
29
- export type PreviewConfig = {
30
- /**
31
- * The `req` object from a Next.js API route. This is given as a parameter to
32
- * the API route.
33
- *
34
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
35
- */
36
- req: {
37
- query: NextApiRequest["query"];
38
- };
39
-
40
- /**
41
- * The `res` object from a Next.js API route. This is given as a parameter to
42
- * the API route.
43
- *
44
- * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
45
- */
46
- res: {
47
- redirect: NextApiResponse["redirect"];
48
- };
49
-
50
- /**
51
- * The Prismic client configured for the preview session's repository.
52
- */
53
- client: Client;
54
-
55
- /**
56
- * A Link Resolver used to resolve the previewed document's URL.
57
- *
58
- * @see To learn more about Link Resolver: {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver}
59
- */
60
- linkResolver?: LinkResolverFunction;
61
-
62
- /**
63
- * The default redirect URL if a URL cannot be determined for the previewed document.
64
- */
65
- defaultURL?: string;
66
- };
23
+ } & ClientConfig;