@prismicio/next 0.1.2 → 0.1.4

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.
@@ -0,0 +1,126 @@
1
+ import * as React from "react";
2
+ import Image, { ImageProps, ImageLoaderProps } from "next/image";
3
+ import { buildURL, ImgixURLParams } from "imgix-url-builder";
4
+ import * as prismicH from "@prismicio/helpers";
5
+ import * as prismicT from "@prismicio/types";
6
+
7
+ import { __PRODUCTION__ } from "./lib/__PRODUCTION__";
8
+ import { devMsg } from "./lib/devMsg";
9
+
10
+ /**
11
+ * Creates a `next/image` loader for Imgix, which Prismic uses, with an optional
12
+ * collection of default Imgix parameters.
13
+ *
14
+ * @see To learn about `next/image` loaders: https://nextjs.org/docs/api-reference/next/image#loader
15
+ * @see To learn about Imgix's URL API: https://docs.imgix.com/apis/rendering
16
+ */
17
+ const imgixLoader = (args: ImageLoaderProps): string => {
18
+ const url = new URL(args.src);
19
+
20
+ const params: ImgixURLParams = {
21
+ fit: (url.searchParams.get("fit") as ImgixURLParams["fit"]) || "max",
22
+ w: args.width,
23
+ h: undefined,
24
+ };
25
+
26
+ if (args.quality) {
27
+ params.q = args.quality;
28
+ }
29
+
30
+ return buildURL(args.src, params);
31
+ };
32
+
33
+ export type PrismicNextImageProps = Omit<
34
+ ImageProps,
35
+ "src" | "alt" | "width" | "height"
36
+ > & {
37
+ /**
38
+ * The Prismic Image field or thumbnail to render.
39
+ */
40
+ field: prismicT.ImageFieldImage | null | undefined;
41
+
42
+ /**
43
+ * An object of Imgix URL API parameters to transform the image.
44
+ *
45
+ * @see https://docs.imgix.com/apis/rendering
46
+ */
47
+ imgixParams?: ImgixURLParams;
48
+
49
+ /**
50
+ * Declare an image as decorative by providing `alt=""`.
51
+ *
52
+ * See:
53
+ * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images
54
+ */
55
+ alt?: "";
56
+
57
+ /**
58
+ * Declare an image as decorative only if the Image field does not have
59
+ * alternative text by providing `fallbackAlt=""`.
60
+ *
61
+ * See:
62
+ * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images
63
+ */
64
+ fallbackAlt?: "";
65
+ };
66
+
67
+ /**
68
+ * React component that renders an image from a Prismic Image field or one of
69
+ * its thumbnails using `next/image`. It will automatically set the `alt`
70
+ * attribute using the Image field's `alt` property.
71
+ *
72
+ * It uses an Imgix URL-based loader by default. A custom loader can be provided
73
+ * with the `loader` prop. If you would like to use the Next.js Image
74
+ * Optimization API instead, set `loader={undefined}`.
75
+ *
76
+ * @param props - Props for the component.
77
+ *
78
+ * @returns A responsive image component using `next/image` for the given Image
79
+ * field.
80
+ *
81
+ * @see To learn more about `next/image`, see: https://nextjs.org/docs/api-reference/next/image
82
+ */
83
+ export const PrismicNextImage = ({
84
+ field,
85
+ imgixParams = {},
86
+ alt,
87
+ fallbackAlt,
88
+ layout,
89
+ ...restProps
90
+ }: PrismicNextImageProps) => {
91
+ if (!__PRODUCTION__) {
92
+ if (typeof alt === "string" && alt !== "") {
93
+ console.warn(
94
+ `[PrismicNextImage] The "alt" prop can only be used to declare an image as decorative by passing an empty string (alt="") but was provided a non-empty string. You can resolve this warning by removing the "alt" prop or changing it to alt="". For more details, see ${devMsg(
95
+ "alt-must-be-an-empty-string",
96
+ )}`,
97
+ );
98
+ }
99
+
100
+ if (typeof fallbackAlt === "string" && fallbackAlt !== "") {
101
+ console.warn(
102
+ `[PrismicNextImage] The "fallbackAlt" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt="") but was provided a non-empty string. You can resolve this warning by removing the "fallbackAlt" prop or changing it to fallbackAlt="". For more details, see ${devMsg(
103
+ "alt-must-be-an-empty-string",
104
+ )}`,
105
+ );
106
+ }
107
+ }
108
+
109
+ if (prismicH.isFilled.imageThumbnail(field)) {
110
+ const src = buildURL(field.url, imgixParams);
111
+
112
+ return (
113
+ <Image
114
+ src={src}
115
+ width={layout === "fill" ? undefined : field.dimensions.width}
116
+ height={layout === "fill" ? undefined : field.dimensions.height}
117
+ alt={alt ?? (field.alt || fallbackAlt)}
118
+ loader={imgixLoader}
119
+ layout={layout}
120
+ {...restProps}
121
+ />
122
+ );
123
+ } else {
124
+ return null;
125
+ }
126
+ };
@@ -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,82 @@ 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
124
+ * path.
125
+ *
126
+ * This is used to prevent infinite refrehes; when
127
+ * `isDescendantOfBasePath` is `false`, `router.isPreview` is also
128
+ * `false`.
129
+ *
130
+ * If the app does not have a base path, this should always be `true`.
131
+ */
132
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(
133
+ window.location.origin + router.basePath,
134
+ );
135
+
136
+ const prismicPreviewCookieRepositoryName =
137
+ getPreviewCookieRepositoryName(prismicPreviewCookie);
138
+
139
+ if (
140
+ locationIsDescendantOfBasePath &&
141
+ prismicPreviewCookieRepositoryName === repositoryName
142
+ ) {
143
+ startPreviewMode();
144
+ }
145
+ }
110
146
  }
111
147
 
112
148
  // On cleanup, unregister Prismic Toolbar event handlers.
113
149
  return () => {
114
- if (window) {
115
- window.removeEventListener(
116
- "prismicPreviewUpdate",
117
- handlePrismicPreviewUpdate,
118
- );
119
- window.removeEventListener(
120
- "prismicPreviewEnd",
121
- handlePrismicPreviewEnd,
122
- );
123
- }
150
+ window.removeEventListener(
151
+ "prismicPreviewUpdate",
152
+ handlePrismicPreviewUpdate,
153
+ );
154
+ window.removeEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
124
155
  };
125
- }, []);
156
+ }, [
157
+ repositoryName,
158
+ resolvedExitPreviewURL,
159
+ resolvedUpdatePreviewURL,
160
+ router.isPreview,
161
+ router.basePath,
162
+ ]);
126
163
 
127
164
  return (
128
165
  <>
129
- <PrismicToolbar repositoryName={repositoryName} />
130
166
  {children}
167
+ <PrismicToolbar repositoryName={repositoryName} />
131
168
  </>
132
169
  );
133
170
  }
@@ -10,7 +10,8 @@ interface PrismicNextPreviewData {
10
10
  *
11
11
  * @param previewData - The Next.js preview data object to check.
12
12
  *
13
- * @returns `true` if `previewData` contains Prismic preview data, `false` otherwise.
13
+ * @returns `true` if `previewData` contains Prismic preview data, `false`
14
+ * otherwise.
14
15
  */
15
16
  const isPrismicNextPreviewData = (
16
17
  previewData: PreviewData,
@@ -45,7 +46,8 @@ export type EnableAutoPreviewsConfig<
45
46
  /**
46
47
  * A Next.js API endpoint request object.
47
48
  *
48
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
49
+ * Pass a `req` object when using `enableAutoPreviews` in a Next.js API
50
+ * endpoint.
49
51
  */
50
52
  req?: HttpRequestLike;
51
53
  }
@@ -60,19 +62,17 @@ export type EnableAutoPreviewsConfig<
60
62
  export const enableAutoPreviews = <TPreviewData extends PreviewData>(
61
63
  config: EnableAutoPreviewsConfig<TPreviewData>,
62
64
  ): void => {
63
- /**
64
- * If preview data is being passed from Next Context then use queryContentFromRef
65
- */
66
65
  if ("previewData" in config && config.previewData) {
66
+ // If preview data is being passed from Next Context then use queryContentFromRef
67
+
67
68
  const { previewData } = config;
68
69
 
69
70
  if (isPrismicNextPreviewData(previewData) && previewData.ref) {
70
71
  config.client.queryContentFromRef(previewData.ref);
71
72
  }
72
- /**
73
- * If the req object is passed then use enableAutoPreviewsFromReq
74
- */
75
73
  } else if ("req" in config && config.req) {
74
+ // If the req object is passed then use enableAutoPreviewsFromReq
75
+
76
76
  config.client.enableAutoPreviewsFromReq(config.req);
77
77
  }
78
78
  };
@@ -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,33 @@
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
11
+ * cookie.
12
+ *
13
+ * @returns The value of the cookie, if it exists.
14
+ */
15
+ export const getPrismicPreviewCookie = (
16
+ cookieJar: string,
17
+ ): string | undefined => {
18
+ const cookies = cookieJar.split("; ");
19
+
20
+ let value: string | undefined;
21
+
22
+ for (const cookie of cookies) {
23
+ const parts = cookie.split("=");
24
+ const name = readValue(parts[0]).replace(/%3D/g, "=");
25
+
26
+ if (name === prismic.cookie.preview) {
27
+ value = readValue(parts.slice(1).join("="));
28
+ continue;
29
+ }
30
+ }
31
+
32
+ return value;
33
+ };
@@ -1,7 +1,6 @@
1
- import { NextApiRequest } from "next";
2
- import { LinkResolverFunction } from "@prismicio/helpers";
3
-
4
- import { PreviewConfig } from "./";
1
+ import type { Client } from "@prismicio/client";
2
+ import type { NextApiRequest, NextApiResponse } from "next";
3
+ import type { LinkResolverFunction } from "@prismicio/helpers";
5
4
 
6
5
  type PrismicNextQuery = {
7
6
  documentId: string;
@@ -18,8 +17,71 @@ type PrismicNextQuery = {
18
17
  */
19
18
  const isPrismicNextQuery = (
20
19
  query: NextApiRequest["query"],
21
- ): query is PrismicNextQuery =>
22
- 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
67
+ * document.
68
+ *
69
+ * **Note**: If you `next.config.js` file contains a `basePath`, the
70
+ * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
71
+ * property using the `basePath` option.
72
+ */
73
+ defaultURL?: string;
74
+
75
+ /**
76
+ * The `basePath` for the Next.js app as it is defined in `next.config.js`.
77
+ * This option can be omitted if the app does not have a `basePath`.
78
+ *
79
+ * @remarks
80
+ * The API route is unable to detect the app's `basePath` automatically. It
81
+ * must be provided to `redirectToPreviewURL()` manually.
82
+ */
83
+ basePath?: string;
84
+ };
23
85
 
24
86
  /**
25
87
  * Redirects a user to the URL of a previewed Prismic document from within a
@@ -28,26 +90,22 @@ const isPrismicNextQuery = (
28
90
  export async function redirectToPreviewURL<
29
91
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
92
  TLinkResolverFunction extends LinkResolverFunction<any>,
31
- >({
32
- req,
33
- res,
34
- client,
35
- linkResolver,
36
- defaultURL = "/",
37
- }: PreviewConfig<TLinkResolverFunction>): Promise<void> {
38
- if (isPrismicNextQuery(req.query)) {
39
- const { documentId, token } = req.query;
40
- const previewUrl = await client.resolvePreviewURL({
41
- linkResolver,
93
+ >(config: RedirectToPreviewURLConfig<TLinkResolverFunction>): Promise<void> {
94
+ const defaultURL = config.defaultURL || "/";
95
+ const basePath = config.basePath || "";
96
+
97
+ if (isPrismicNextQuery(config.req.query)) {
98
+ const previewUrl = await config.client.resolvePreviewURL({
99
+ linkResolver: config.linkResolver,
42
100
  defaultURL,
43
- documentID: documentId,
44
- previewToken: token,
101
+ documentID: config.req.query.documentId,
102
+ previewToken: config.req.query.token,
45
103
  });
46
104
 
47
- res.redirect(previewUrl);
105
+ config.res.redirect(basePath + previewUrl);
48
106
 
49
107
  return;
50
108
  }
51
109
 
52
- res.redirect(defaultURL);
110
+ config.res.redirect(basePath + defaultURL);
53
111
  }