Skip to content

Commit

Permalink
fix(preview): use absolute redirect url for draft api routes (#504)
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiazom authored Aug 23, 2024
1 parent 67eb27a commit 2aa0a23
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 7 deletions.
2 changes: 1 addition & 1 deletion sanity.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default defineConfig({
visionTool({ defaultApiVersion: apiVersion }),
presentationTool({
previewUrl: {
draftMode: {
previewMode: {
enable: "/api/draft",
},
},
Expand Down
4 changes: 2 additions & 2 deletions src/app/api/disable-draft/route.ts
Original file line number Diff line number Diff line change
@@ -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, "/"));
}
11 changes: 7 additions & 4 deletions src/app/api/draft/route.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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 });
Expand Down
16 changes: 16 additions & 0 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit 2aa0a23

Please sign in to comment.