Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website.

While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update.

This was the code snippet I was originally working with to determine the status of preview mode:

import groq from 'groq';
import { previewData } from "next/headers"

const query = groq`
  *[_type=='post']{
    ...,
    author->,
    categories[]->,
  } | order(_createAt desc)`;

export default function Home() {
  if (previewData()) {
    return (
      <div><h1>In preview mode</h1></div>
    )
  }
  return (
    <div><h1>Not in preview mode</h1></div>

  )
}

However, it seems that previewData() is no longer exported by next/headers, leaving me unsure of how to proceed further.

I attempted using getServerSideProps but discovered that it cannot be utilized in the app directory within NextJs 13.

Even after consulting the Sanity documentation for guidance, I have yet to find a solution to resolve this issue.

Answer №1

Finally, after spending a few hours searching for the answer, I have discovered it.

You can find the necessary documentation here: (NextJs DraftMode)

Preview mode has been replaced with DraftMode

If you want to check whether your API is in DraftMode or not, here is the code snippet for the frontend:

export default function Home() {
  const { isEnabled } = draftMode();
  return (
    <main>
      <h1>My Blog Post</h1>
      <p>Draft Mode is currently {isEnabled ? 'Enabled' : 'Disabled'}</p>
    </main>
  );
}

The corresponding API calls are located in app/api/draft/route.ts and app/api/exit-draft/route.ts.

import { draftMode } from 'next/headers';

export async function GET(request: Request) {
    draftMode().enable();
    return new Response('Draft mode is enabled');
}

To exit out of draftmode, go to /api/exit-draft.

import { draftMode } from 'next/headers';

export async function GET(request: Request) {
    draftMode().disable();
    return new Response('Draft mode is disabled');
}

It took some time to figure this out. Ultimately, make sure to properly set up your routes instead of directly calling the API.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble aligning image and expanding video to fit the screen in a NextJS application

I need help with: centering the image above the waitlist sign up scaling the background video in a relative way to fill the screen regardless of browser size This is the relevant part of index.js: import Head from 'next/head' import Image from ...

Retrieve a specific item from the ngrx/store

My Reducer implementation in my Angular 2 app is designed to store state items related to price offers for Financial Instruments, such as stocks and currencies. This is the implementation of my Reducer: export const offersStore = (state = new Array<Of ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

Next.js with Express Application Deployment to Elastic Beanstalk: Troubleshooting Error 502

I am encountering persistent 502 Bad Gateway errors while attempting to deploy a next.js application using express to Electric Beanstalk. 2020/03/02 15:26:28 [error] 8286#0: *172 connect() failed (111: Connection refused) while connecting to upstream, ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

Creating a Bottom Sliding Menu in Ionic 2

Hey there! I'm working on something that might not fit the typical definition of a sliding menu. It's not for navigation purposes, but rather to house some data. My idea for this actually comes from Apple Maps: https://i.stack.imgur.com/hL1RU.jp ...

Exploring the mechanics behind optional chaining, known as the Elvis operator, in TypeScript. How does this feature operate within the

Can someone explain the concept of optional chaining (Elvis operator) in TypeScript and how it can be used effectively? public static getName(user: IUser){ if(user.firstName != null && user.firstName != ""){ return user.firstName; } ...

Shopify app authentication using koa-shopify-auth for seamless user access

Recently, I developed a React front end based on the guide provided at The project involves a unique setup; it's a NextJs and React application with a custom Koa server to serve the NextJs app. The Koa server integrates the koa-ashopify-auth package ...

Seeking guidance on how to retrieve an image from Firebase storage using NextJs. Any suggestions on how to tackle this issue

Here is the code snippet we are currently utilizing in Nextjs to facilitate image downloads: const handleDownload = async (fileUrl: string) => { try { const storageRef = ref(storage, fileUrl); const downloadURL = await getDownloadURL(storageRe ...

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

Is there a way to expand the color options of mui using Typescript?

I'm attempting to expand the color options provided by mui. While overriding primary, secondary, and other preset colors works smoothly, I'm struggling with creating a custom set of colors right after. Despite numerous examples available without ...

The loading of SCSS modules is delayed in a NextJS project using Mantine

In my current NextJS project, I am utilizing Mantine for UI components and implementing custom styles using SCSS modules. The project also involves Typescript. Everything appears to be functioning correctly during development; however, when looking at the ...

What is the process for transforming a String into an HTML element within a Next JS Application?

I stored the product description as HTML elements in a Database, but when I try to render this data into a div, it displays as a String. I am looking to showcase all the data as HTML elements in my Next JS application. I attempted using JSON.parse, but unf ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

The rule "react/jsx-sort-props" does not have a valid configuration

I've been attempting to organize props names alphabetically using the eslint-plugin-react plugin but I keep encountering this error: [Error ] .eslintrc.json: Configuration for rule "react/jsx-sort-props" is invalid: Value {"callbacksLast":true,"shorth ...

When working with Web Workers in Jest, you may encounter an error stating "Cannot use 'import.meta' outside a module."

I'm currently developing a web application using nextjs 10.1.3. To improve performance, we have integrated a web worker on one of the pages and intend to add more workers in the future. All our code is thoroughly unit tested, and with the use of the w ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Render function in Next.js did not yield anything

Recently, I came across the next.js technology and encountered an error. Can anyone help me solve this issue? What could be causing it?View image here import React from 'react' import Button from "../components/button" function HomePa ...