Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to connect to overlays. Make sure you're calling the 'enableOverlays' function in '@sanity/overlays' correctly #671

Open
xnslx opened this issue Jan 10, 2024 · 9 comments

Comments

@xnslx
Copy link

xnslx commented Jan 10, 2024

I am trying to install Presentation tool to my hydrogen project. It works perfectly in the development mode. But there is no way to make it work in the production mode. I think it will be very neat to switch between an optimized production mode and an authorized mode to fetch draft content and edit. The error message is PresentationTool-q3Ixv-a7-4a2ea8d5.js:95 Unable to connect to overlays. Make sure you're calling the 'enableOverlays' function in '@sanity/overlays' correctly

Here are the related code.

/studio/sanity.config.ts

const previewUrl =
  process.env.MODE == 'development'
    ? 'http://localhost:3000'
    : 'https://example.vercel.app/'

plugins: [
   ...,
    presentationTool({
      previewUrl: {
        origin: previewUrl,
        draftMode: {
          enable: '/draft',
        },
      },
      locate,
    }),
    ...(isDev ? devOnlyPlugins : []),
  ],
...
/studio/locate.ts

import {DocumentLocationResolver} from 'sanity/presentation'
import {map} from 'rxjs'

// Pass 'context' as the second argument
export const locate: DocumentLocationResolver = (params, context) => {
  // Set up locations for post documents
  if (params.type === 'journal') {
    // Subscribe to the latest slug and title
    const doc$ = context.documentStore.listenQuery(
      `*[_id == $id][0]{slug,title}`,
      params,
      {perspective: 'previewDrafts'} // returns a draft article if it exists
    )
    // Return a streaming list of locations
    return doc$.pipe(
      map((doc) => {
        // If the document doesn't exist or have a slug, return null
        if (!doc || !doc.slug?.current) {
          return null
        }
        return {
          locations: [
            {
              title: doc.title || 'Untitled',
              href: `/journals/${doc.slug.current}`,
            },
            {
              title: 'Journals',
              href: '/',
            },
          ],
        }
      })
    )
  }
  return null
}
/app/routes/draft.ts

...imports

export const loader: LoaderFunction = async function ({request, context}) {
  const {searchParams} = new URL(request.url);

  const secret = searchParams.get('sanity-preview-secret');
  const pathName = searchParams.get('sanity-preview-pathname');
  if (!pathName || secret == null || !secret || secret == null)
    return redirect('/', {
      status: 307,
    });

  return redirect(`${pathName}`, {
    status: 307,
  });
};
/app/components/VisualEditing.tsx

...imports

async function loader({context}: LoaderArgs) {
  const {env} = context;
  return json({env});
}

export default function VisualEditing() {
  const {env} = useLoaderData();

  const url =
    env.NODE_ENV == 'development'
      ? 'http://localhost:3333'
      : 'https://example-studio.vercel.app/structure';

  const client = createClient({
    projectId: env.SANITY_PROJECT_ID,
    dataset: env.SANITY_DATASET,
    apiVersion: 'v2022-05-01',
    useCdn: true,
    stega: {
      enabled: true,
      studioUrl: url,
    },
  });

  const navigateRemix = useNavigate();
  const navigateComposerRef = useRef<null | ((update: HistoryUpdate) => void)>(
    null,
  );

  useEffect(() => {
    const disable = enableOverlays({
      history: {
        subscribe: (navigate) => {
          navigateComposerRef.current = navigate;
          return () => {
            navigateComposerRef.current = null;
          };
        },
        update: (update) => {
          if (update.type === 'push' || update.type === 'replace') {
            navigateRemix(update.url, {
              replace: update.type === 'replace',
            });
          } else if (update.type === 'pop') {
            navigateRemix(-1);
          }
        },
      },
    });
    return () => disable();
  }, [navigateRemix]);

  const location = useLocation();

  useEffect(() => {
    if (navigateComposerRef.current) {
      navigateComposerRef.current({
        type: 'push',
        url: `${location.pathname}${location.search}${location.hash}`,
      });
    }
  }, [location.pathname, location.search, location.hash]);

  useLiveMode({client});

  return null;
}

This is in production. The Edit button on the left cannot be toggled.
IMG_7749

@Brams-s
Copy link

Brams-s commented Jan 18, 2024

Facing a similar issue in development as well while following the guide on [https://www.sanity.io/guides/nextjs-app-router-live-preview](the official sanity app router guide)

@xnslx
Copy link
Author

xnslx commented Jan 19, 2024

Facing a similar issue in development as well while following the guide on [https://www.sanity.io/guides/nextjs-app-router-live-preview](the official sanity app router guide)

Hey, what is the error in the console? This answer helps me. #556 (comment)

@Brams-s
Copy link

Brams-s commented Jan 19, 2024

Facing a similar issue in development as well while following the guide on [https://www.sanity.io/guides/nextjs-app-router-live-preview](the official sanity app router guide)

Hey, what is the error in the console? This answer helps me. #556 (comment)

Hey! Seeing the following error in the console:
Screenshot 2024-01-19 at 15 34 15

It is being used as follows:

"use client";

import type { HistoryAdapterNavigate } from "@sanity/overlays";
import { useEffect, useRef, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { enableOverlays } from "@sanity/overlays";
import { useLiveMode } from "@sanity/react-loader";

import { client } from "~/sanity/lib/client";

// Always enable stega in Live Mode
const stegaClient = client.withConfig({ stega: true });

export default function VisualEditing() {
  const router = useRouter();
  const routerRef = useRef(router);
  const [navigate, setNavigate] = useState<
    HistoryAdapterNavigate | undefined
  >();

  useEffect(() => {
    routerRef.current = router;
  }, [router]);
  useEffect(() => {
    const disable = enableOverlays({
      history: {
        subscribe: (navigate) => {
          setNavigate(() => navigate);
          return () => setNavigate(undefined);
        },

Also just ran turbo clean:workspaces && turbo clean as per some suggestions in the linked comment but no luck unfortunately

@xnslx
Copy link
Author

xnslx commented Jan 19, 2024

Facing a similar issue in development as well while following the guide on [https://www.sanity.io/guides/nextjs-app-router-live-preview](the official sanity app router guide)

Hey, what is the error in the console? This answer helps me. #556 (comment)

Hey! Seeing the following error in the console: Screenshot 2024-01-19 at 15 34 15

It is being used as follows:

"use client";

import type { HistoryAdapterNavigate } from "@sanity/overlays";
import { useEffect, useRef, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { enableOverlays } from "@sanity/overlays";
import { useLiveMode } from "@sanity/react-loader";

import { client } from "~/sanity/lib/client";

// Always enable stega in Live Mode
const stegaClient = client.withConfig({ stega: true });

export default function VisualEditing() {
  const router = useRouter();
  const routerRef = useRef(router);
  const [navigate, setNavigate] = useState<
    HistoryAdapterNavigate | undefined
  >();

  useEffect(() => {
    routerRef.current = router;
  }, [router]);
  useEffect(() => {
    const disable = enableOverlays({
      history: {
        subscribe: (navigate) => {
          setNavigate(() => navigate);
          return () => setNavigate(undefined);
        },

Also just ran turbo clean:workspaces && turbo clean as per some suggestions in the linked comment but no luck unfortunately

Check your session cookie, making sure that when clicking the Presentation button in the studio, SANITY_STUDIO_PREVIEW_URL is redirected to your frontend route, routes/api/draft which sets the session cookie, but I notice that using Next, it has a default draftMode which you can enable. This is my VisualEditingcomponent

import {useLoaderData, useLocation, useNavigate} from '@remix-run/react';
import {
  HistoryAdapter,
  HistoryAdapterNavigate,
  HistoryUpdate,
  enableOverlays,
} from '@sanity/overlays';
import {LoaderArgs, json} from '@shopify/remix-oxygen';
import {useEffect, useRef} from 'react';
import {useLiveMode} from '@sanity/react-loader';
import {createClient} from '@sanity/client/stega';
import {getSession} from '~/lib/sanity/preview';

async function loader({context, request}: LoaderArgs) {
  const {env} = context;
  const session = await getSession(request.headers.get('Cookie'));
  const previewToken = session.get('token');
  return json({env, previewToken});
}

export default function VisualEditing() {
  const {env, previewToken} = useLoaderData();

  const url =
    env.NODE_ENV == 'development'
      ? 'http://localhost:3333'
      : 'https://example-studio.vercel.app/structure';

  const client = createClient({
    projectId: env.SANITY_PROJECT_ID,
    dataset: env.SANITY_DATASET,
    apiVersion: 'v2022-05-01',
    useCdn: false,
    perspective: previewToken ? 'previewDrafts' : 'published',
    // The 'stega' object groups stega-specific options
    stega: {
      enabled: previewToken ? true : false,
      studioUrl: url,
    },
  });

  const stegaClient = client.withConfig({
    stega: true,
  });

  const navigateRemix = useNavigate();
  const navigateComposerRef = useRef<null | ((update: HistoryUpdate) => void)>(
    null,
  );

  useEffect(() => {
    const disable = enableOverlays({
      history: {
        subscribe: (navigate) => {
          navigateComposerRef.current = navigate;
          return () => {
            navigateComposerRef.current = null;
          };
        },
        update: (update) => {
          if (update.type === 'push' || update.type === 'replace') {
            navigateRemix(update.url, {
              replace: update.type === 'replace',
            });
          } else if (update.type === 'pop') {
            navigateRemix(-1);
          }
        },
      },
    });
    return () => disable();
  }, [navigateRemix]);

  const location = useLocation();

  useEffect(() => {
    if (navigateComposerRef.current) {
      navigateComposerRef.current({
        type: 'push',
        url: `${location.pathname}${location.search}${location.hash}`,
      });
    }
  }, [location.pathname, location.search, location.hash]);

  useLiveMode({client: stegaClient, studioUrl: url});
  return null;
}

@rdunk
Copy link
Member

rdunk commented Apr 2, 2024

Can you confirm if this is still an issue using the latest packages, i.e. using @sanity/visual-editing over @sanity/overlays?

@DanielHirunrusme
Copy link

confirmed this is still an issue

@abwhb
Copy link

abwhb commented Apr 24, 2024

any possible solution for this?

@rdunk
Copy link
Member

rdunk commented Apr 24, 2024

This generally happens as a result of misconfiguration somewhere, essentially a connection between the application and Presentation tool is unable to be established. The code examples in this comment thread are outdated so it's very difficult to give feedback on what the specific problem might be.

Our plan is to work on proactively detecting misconfiguration issues to provide better upfront warnings, until then it would be helpful if anyone seeing the same issue is able to share more context like framework, package version numbers, tool configuration, etc. Thanks.

@manyamOpenthrive
Copy link

I'm currently working on a Next.js project and integrating Sanity with a presentation tool. However, I've encountered the following error:

(PresentationTool-2QKQ3IHD.js?v=d3749efe:1359 Unable to connect to visual editing. Make sure you've setup '@sanity/visual-editing' correctly)

I've thoroughly gone through the documentation related to @sanity/visual-editing, but I haven't been able to resolve the issue. Could you kindly provide guidance or point me in the right direction to fix this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants