👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Discussion about resolving an issue with preview mode not logging out properly and causing errors.

45 replies
Last updated: Jun 26, 2023
How can I solve a problem where when you logout during a Preview mode from the studio and return back to the website that it removes the cookie or cache?I am getting an error after logging out that I have no access to the preview mode because I am not logged in, resulting in the app crashing. I have to manually remove the cookies in order to make it work.


to load resource: the server responded with a status of 404 ()
26488-4e81157118c9fc11.js:1 Error: Unable to load preview as you're not logged in
    at onPublicAccessOnly (9151-fc58c70d1eec9468.js:1:10281)
    at 9151-fc58c70d1eec9468.js:1:12816
    at s.default (9151-fc58c70d1eec9468.js:1:9360)
    at rs (bce60fc1-d12f33ec043fc570.js:9:38883)
    at lg (bce60fc1-d12f33ec043fc570.js:9:54283)
    at iv (bce60fc1-d12f33ec043fc570.js:9:112451)
    at oR (bce60fc1-d12f33ec043fc570.js:9:90087)
    at bce60fc1-d12f33ec043fc570.js:9:89936
    at oD (bce60fc1-d12f33ec043fc570.js:9:89943)
    at ow (bce60fc1-d12f33ec043fc570.js:9:87645)
window.console.error @ 6488-4e81157118c9fc11.js:1
<http://sociaaladvocatenrotterdam.vercel.app/:1|sociaaladvocatenrotterdam.vercel.app/:1>     Failed 

sanity.preview.ts:

"use client"

import { definePreview } from "next-sanity/preview"
import type { UsePreview } from "next-sanity/preview"
import { config } from "./sanity.client"

const onPublicAccessOnly = () => {
  throw new Error(`Unable to load preview as you're not logged in`)
}

export const usePreview: UsePreview = definePreview({
  projectId: config.projectId,
  dataset: config.dataset,
  onPublicAccessOnly
})

page.tsx:

import { draftMode } from "next/headers"
import { notFound } from "next/navigation"

import { getPage, getPageMeta } from "@/lib/sanity/sanity.helpers"

import { PageLayout } from "@/components/layout"
import { ExitPreviewMode, MetaData } from "@/components/shared"
import { PagePreview, PreviewSuspense } from "@/components/previews"

import { pageQuery } from "@/lib/queries"

export const generateMetadata = async () => {
  const page = await getPageMeta("frontpage")

  return MetaData({ page })
}

export const revalidate = 60 // revalidate this page every 60 seconds

const HomePage = async () => {
  const { isEnabled } = draftMode()

  const page = await getPage("frontpage")

  if (!page) {
    notFound()
  }

  if (isEnabled) {
    return (
      <PreviewSuspense fallback={<PageLayout page={page} />}>
        <PagePreview query={pageQuery} variables={{ slug: "frontpage" }} />
        <ExitPreviewMode />
      </PreviewSuspense>
    )
  }

  return <PageLayout page={page} />
}

export default HomePage
Jun 13, 2023, 9:03 AM
I have seen examples where an area on the header (on your site) checks if you are in preview mode (draft). If it is, a text will appear saying something like "you are in preview... click link to exit". The link will then call the exit preview page and remove the cookie. It's not exactly what you asked but it fits nicely imo.
Jun 13, 2023, 9:36 AM
Could you share the link?
Jun 13, 2023, 10:42 AM
Well I do i have ExitPrevieMode shows a button Exit preview mode. But Once you logout and refresh the page page will crash
Jun 13, 2023, 10:42 AM
But the problem is I am not logged in to the STudio anymore. ANd the Preview button still showing. Only removes if cookies are deleted
Jun 13, 2023, 10:49 AM
yeah I understand now, my bad.
Jun 13, 2023, 11:50 AM
The moment you click on “logout” from the Studio while a page or post is still in preview mode and when you return to the homepage page will crash saying you are not logged in to use preview mode. This is still active
Jun 13, 2023, 11:54 AM
what I was suggesting was a link (on your website, like in the header) to disable preview (
/api/exit-preview
for example). you would display the link only if you are in preview.
Jun 13, 2023, 11:55 AM
this will effectively clear the cookies and let you go back to live content
Jun 13, 2023, 11:55 AM
I have that yes. My button is “Exit preview mode” and a link to the api exit preview
Jun 13, 2023, 11:55 AM
It works if you are logged in
Jun 13, 2023, 11:55 AM
I see
Jun 13, 2023, 11:56 AM
But once you logout cookies are still there
Jun 13, 2023, 11:56 AM
When i comment code isDraft it works
Jun 13, 2023, 11:56 AM
So something is missing there
Jun 13, 2023, 11:56 AM
that's odd, it should not matter really as this is the Next draft mode implementation and should not interfere with Sanity imo
Jun 13, 2023, 11:56 AM
Was hoping that Sanity has a function to check if user is logged in
Jun 13, 2023, 11:56 AM
If you are ysing previews could you test this?
Jun 13, 2023, 11:57 AM
Same action
Jun 13, 2023, 11:57 AM
I could try
Jun 13, 2023, 11:57 AM
Like logging out
Jun 13, 2023, 11:57 AM
while in preview
Jun 13, 2023, 11:57 AM
See what happens
Jun 13, 2023, 11:57 AM
Thanks
Jun 13, 2023, 11:57 AM
works for me
Jun 13, 2023, 11:59 AM
How do you check if you are in preview mode?
Jun 13, 2023, 11:59 AM
Do you use “pages” or “app” folder
Jun 13, 2023, 11:59 AM
I am usingg isDraft new function in next 13
Jun 13, 2023, 12:00 PM
I don't (haven't implemented it yet) but I just logged out while in preview and got the same error. Then I manually went to the exit preview page and it's all good
Jun 13, 2023, 12:00 PM
So its a bug
Jun 13, 2023, 12:00 PM
yeah, I'd say that's the way for checking (I'm not using drafts yet)
Jun 13, 2023, 12:00 PM
Somewhere
Jun 13, 2023, 12:00 PM
good to know
Jun 13, 2023, 12:00 PM
still the good old preview and pages routes
Jun 13, 2023, 12:01 PM
try to go manually to the exit preview page and check, it should work
Jun 13, 2023, 12:02 PM
Works manually yes
Jun 13, 2023, 12:03 PM
what error do you get when you check
isDraft()
?
Jun 13, 2023, 12:04 PM
But when you set to return null the Button is still showing to exit preview mode even if not logged in and to delete the cookies.
Jun 13, 2023, 12:07 PM
import { definePreview } from "next-sanity/preview"
import type { UsePreview } from "next-sanity/preview"
import { config } from "./sanity.client"

const exitPreviewMode = async () => {
  const exitPreviewUrl = "/api/exit-preview"

  try {
    const response = await fetch(exitPreviewUrl)

    if (response.ok) {
      console.log("Exited preview mode successfully.")
    } else {
      console.error("Failed to exit preview mode:", response.statusText)
    }
  } catch (error) {
    console.error("Failed to exit preview mode:", error)
  }
}

const onPublicAccessOnly = () => {
  exitPreviewMode()
}

export const usePreview: UsePreview = definePreview({
  projectId: config.projectId,
  dataset: config.dataset,
  onPublicAccessOnly
})
Jun 13, 2023, 12:17 PM
Let's see if this works 😄
Jun 13, 2023, 12:17 PM
🙂 I was trying something similar just now
Jun 13, 2023, 12:18 PM
import { definePreview } from "next-sanity/preview";
import type { UsePreview } from "next-sanity/preview";
import { config } from "./sanity.client";

const exitPreviewMode = async () => {
  const exitPreviewUrl = "/api/exit-preview";

  try {
    const response = await fetch(exitPreviewUrl);

    if (response.ok) {
      console.log("Exited preview mode successfully.");
      location.reload(); // Refresh the page
    } else {
      console.error("Failed to exit preview mode:", response.statusText);
    }
  } catch (error) {
    console.error("Failed to exit preview mode:", error);
  }
};

const onPublicAccessOnly = () => {
  exitPreviewMode();
};

export const usePreview: UsePreview = definePreview({
  projectId: config.projectId,
  dataset: config.dataset,
  onPublicAccessOnly,
});
Jun 13, 2023, 12:19 PM
yeah, that looks good
Jun 13, 2023, 12:22 PM
Lets see
Jun 13, 2023, 12:25 PM
🤞
Jun 13, 2023, 12:26 PM
Hi Nino, were you able to solve this? I am stuck on the same error message currently, while trying to implement live preview in a next js 13.4 pages dir project.
Jun 26, 2023, 9:54 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?