next-sanity icon indicating copy to clipboard operation
next-sanity copied to clipboard

Not authenticated - preview not available

Open kamerat opened this issue 2 years ago • 1 comments

This issue is the same as my previous closed one: #38. Reason I create a new issue is to make it simpler to understand as I've come to find a easy way to reproduce this.

If you wrap createPreviewSubscriptionHook in a wrapper component, it will trigger this infinite "Not authenticated - preview not available" loop.

example:

// sanity.ts
const config = {
    projectId: 'xxxxxx',
    dataset: 'xxxx',
    apiVersion: '2021-03-25',
    useCdn: process.env.NODE_ENV === 'production',
    token: ''
};

export const sanityClient= ({ usePreview, locale }: any) => {
    const configCopy = JSON.parse(JSON.stringify(config));
    
    // IDEA: option to switch dataset based on locale parameter
    // configCopy.dataset = locale

    if (usePreview) {
        configCopy.useCdn = false;
        configCopy.token = process.env.SANITY_API_TOKEN as string;
    }

    return createClient(configCopy);
};

// Creates infinite loop - Simple way to reproduce 
export const usePreviewSubscription = () => createPreviewSubscriptionHook({ ...config });

// Creates infinite loop - My ideal usecase
export const usePreviewSubscription = (locale) => createPreviewSubscriptionHook({ ...config, dataset: locale });

// Works, but not for my use case (switch dataset based on locale)
export const usePreviewSubscription = createPreviewSubscriptionHook({ ...config });
// pages/mypage.tsx
    const previewSubscription = usePreviewSubscription;

    const { data: previewContents } = previewSubscription(data?.query, {
        params: data?.queryParams ?? {},
        initialData: [data?.page],
        enabled: preview,
    });

    // Client-side uses the same query, so we may need to filter it down again
    const page = filterDataToSingleItem(previewContents, preview);

kamerat avatar Apr 27 '22 09:04 kamerat

Yeah this is most likely due to how most browsers have started blocking cookies to third party origins.

We're working on a new version of preview mode, and in the draft PR there's a link to a couple of examples that implements the token flow, which works in browsers like Safari :)

stipsan avatar Aug 12 '22 17:08 stipsan

We've just released v2.0.0 which has docs that shows how you can use custom token auth that solves the problem you've experienced here 😌

stipsan avatar Nov 16 '22 16:11 stipsan