SimeonGriggs / sanity-nextjs-preview

Sanity Studio Visual Editing examples for Next.js 14 App + Pages routers
https://sanity-nextjs-preview-two.vercel.app
81 stars 19 forks source link

Iframe Pane Plugin does not redirect to expected post page #8

Closed kenjinakata closed 1 year ago

kenjinakata commented 1 year ago

I'm in the process of working with the Iframe Pane plugin from the documentation. However, when I try to access the preview using the slug URL, I don't see the expected individual post page. Instead, it redirects me to the index page where all the posts are displayed. Do i have to update the preview route?

// sanity/desk/defaultDocumentNode.ts

import { DefaultDocumentNodeResolver } from 'sanity/desk'
import Iframe from 'sanity-plugin-iframe-pane'

export const defaultDocumentNode: DefaultDocumentNodeResolver = (S, { schemaType }) => {
    switch (schemaType) {
        case `post`:
            return S.document().views([
                S.view.form(),
                S.view
                    .component(Iframe)
                    .options({
                        url: (doc: any) => doc?.slug?.current
                            ? `http://localhost:3000/api/preview?slug=${doc.slug.current}`
                            : `http://localhost:3000/api/preview`,
                    })
                    .title('Preview'),
            ])
        default:
            return S.document().views([S.view.form()])
    }
}
// api/preview/route.ts

import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

export async function GET() {
    draftMode().enable();
    redirect(`/`);
}
Screenshot 2023-08-02 at 15 06 31
kenjinakata commented 1 year ago

Fixed it by changing the preview route (Pls let me know if it's a better way):

import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

export async function GET(request: Request) {
    draftMode().enable();

    const url = new URL(request.url);
    const slug = (url.searchParams.get("slug") || "/")

    if (slug === "/") {
        return redirect("/");
    } else {
        redirect(`/${slug}`)
    }
}