diff --git a/sanity.config.ts b/sanity.config.ts index b5b824061..d6f1d633b 100644 --- a/sanity.config.ts +++ b/sanity.config.ts @@ -27,7 +27,7 @@ export default defineConfig({ visionTool({ defaultApiVersion: apiVersion }), presentationTool({ previewUrl: { - draftMode: { + previewMode: { enable: "/api/draft", }, }, diff --git a/src/app/api/disable-draft/route.ts b/src/app/api/disable-draft/route.ts index 426d2041f..84f9e878f 100644 --- a/src/app/api/disable-draft/route.ts +++ b/src/app/api/disable-draft/route.ts @@ -1,8 +1,8 @@ import { draftMode } from "next/headers"; import { NextRequest, NextResponse } from "next/server"; +import { absoluteUrlFromNextRequest } from "src/utils/url"; export function GET(request: NextRequest) { draftMode().disable(); - const url = new URL(request.nextUrl); - return NextResponse.redirect(new URL("/", url.origin)); + return NextResponse.redirect(absoluteUrlFromNextRequest(request, "/")); } diff --git a/src/app/api/draft/route.ts b/src/app/api/draft/route.ts index cffde6923..a4f4b2ed8 100644 --- a/src/app/api/draft/route.ts +++ b/src/app/api/draft/route.ts @@ -1,17 +1,18 @@ import { validatePreviewUrl } from "@sanity/preview-url-secret"; import { draftMode } from "next/headers"; -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { client } from "studio/lib/client"; import { token } from "studio/lib/token"; +import { absoluteUrlFromNextRequest } from "src/utils/url"; const clientWithToken = client.withConfig({ token }); -export async function GET(request: Request) { +export async function GET(request: NextRequest) { try { const { isValid, redirectTo = "/" } = await validatePreviewUrl( clientWithToken, - request.url + request.url, ); if (!isValid) { @@ -20,7 +21,9 @@ export async function GET(request: Request) { draftMode().enable(); - return NextResponse.redirect(redirectTo); + return NextResponse.redirect( + absoluteUrlFromNextRequest(request, redirectTo), + ); } catch (error) { console.error("Error in /api/draft:", error); return new Response("Internal Server Error", { status: 500 }); diff --git a/src/utils/url.ts b/src/utils/url.ts new file mode 100644 index 000000000..154b8974c --- /dev/null +++ b/src/utils/url.ts @@ -0,0 +1,16 @@ +import { NextRequest } from "next/server"; + +export function absoluteUrlFromNextRequest( + request: NextRequest, + pathname?: string, +) { + /** + * useful for middleware redirects where absolute url is required + * https://nextjs.org/docs/messages/middleware-relative-urls#possible-ways-to-fix-it + */ + const absoluteUrl = request.nextUrl.clone(); + if (pathname !== undefined) { + absoluteUrl.pathname = pathname; + } + return absoluteUrl; +}