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

What are some characteristics I can examine in TypeScript?

My understanding of how property checking works in TypeScript was put to the test recently. I noticed that in a specific example, checking for .bold worked fine, but when trying to check for .type, I ran into some confusion. type CustomText = { bold: ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

I am facing an issue where react-syntax-highlighter does not seem to be compatible with Tail

When it comes to displaying sanity block content, I am utilizing the [@sanity/block-content-to-react](@sanity/block-content-to-react) plugin. The BlockContent component is enclosed within a div that has the class "prose". <div className="prose pro ...

callbacks in amazon-cognito-identity-js

When working with amazon-cognito-identity-js, I encountered an issue with the callback function. This is what it currently looks like: cognitoUser?.getUserAttributes((err, results) => { if (err) { console.log(err.message || JSON.stringify(err)); ...

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

What could be causing AWS Elastic Beanstalk to fail in passing the custom JWT?

I have recently deployed a Next.js with Next-Auth project on AWS EB and everything seems to be in order. However, I am encountering an issue with the sign-in form. The browser console is showing the following error: 502 Bad Gateway: POST http://----.elas ...

Is the transcluded content visible to the class as a whole?

Angular2 makes it simple to create a component like this: @Component({ selector: 'some', properties: ['header'] }) @View({ template: ` <div> <h2>{{ getFormattedHeader() }}</h2> <p><conte ...

What is the best way to change the name of an imported variable currently named `await` to avoid conflicting with other variables?

Here is the given code snippet: import * as fs from 'fs'; import {promises as fsPromises} from 'fs'; // ... // Reading the file without encoding to access raw buffer. const { bytesRead, buffer as fileBuffer } = await fsPromises.read( ...

There is no such property - Axios and TypeScript

I am attempting to retrieve data from a Google spreadsheet using axios in Vue3 & TypeScript for the first time. This is my initial experience with Vue3, as opposed to Vue2. Upon running the code, I encountered this error: Property 'items' does ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

The interface 'HTMLIonIconElement' is not able to extend both 'IonIcon' and 'HTMLStencilElement' types at the same time

After upgrading my Angular Ionic app to use Angular v13 from Angular 12 with the command ng update, I encountered errors preventing me from running the application successfully. [ng] Error: node_modules/ionicons/dist/types/components.d.ts:66:15 - error TS2 ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

The error message "ReferenceError: document is not defined inside a Next.js client-side component"

I have a client module called "use client" that I built using Next.js "use client" import type { ReactPortal } from "react" import { createPortal } from "react-dom" interface PortalProps { children: React.ReactNode } export function Portal(props: Port ...

Convert all key types into arrays of that key type using a TypeScript utility type

My interface (type) is currently defined as: interface User { name: string, id: string, age: number, town: string } I have a function now that will search for Users based on specific fields. I prefer not to manually declare an additi ...

The ngx-treeview is displaying an inaccurate tree structure. Can you pinpoint where the issue lies?

I have structured my JSON data following the format used in ngx-treeview. Here is the JSON file I am working with: [ { "internalDisabled": false, "internalChecked": false, "internalCollapsed": false, "text": "JOURNEY", "value": 1 } ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Arranging Pipe Methods in RxJS/Observable for Optimal Functionality

In the class Some, there is a method called run that returns an Observable and contains a pipe within itself. Another pipe is used when executing the run method. import { of } from 'rxjs'; import { map, tap, delay } from 'rxjs/operators&ap ...

i18next fails to update the language in a Next.js application

Utilizing i18next for localization has been quite successful in translating English text to Arabic {t("title")} ==> مرحبا. However, I'm facing an issue when attempting to switch the language back to English using the following code: ...

Encountering the issue: "Unable to establish validator property on string 'control'"

Has anyone encountered this error message before? TypeError: Cannot create property 'validator' on string 'control'" import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core'; import { CommonModule } from &ap ...

Steps for deploying a NextJs Project on the cPanel of a free hosting platform

Looking for some guidance on how to upload my Next.js Project onto a free hosting Cpanel. I've tried various references, but haven't had much luck so far. After executing 'next build', no build folder is being created. Any advice on how ...