How to check Preview Mode or Edit mode in API?

I've few API, when I try to get data in preview page, it's always return live data,

I've debug, the function to get preview mode always return live mode, how I can get correct state here, do we have a function support it?


Environment

  • Xperience by Kentico version: 31.0.0

  • .NET version: 8

Tags:
Content querying Page Builder

Answers

Suggestions:

  1. Use the Content Retriever. It automatically applies the request context (preview/live) to the content query and will retrieve unpublished content when viewing a page in the Page Builder or Preview tabs in the admin UI (based on the request URL). It will automatically switch to only retrieve published items when requests are made on the live website. You don't need to use any special APIs or configure the querying based on the request mode.
  2. Use the ContentItemQueryBuilder, which is a low-level API. It requires you to manually pass the preview context state to the query to retrieve unpublished content. You can use IWebsiteChannelContext.IsPreview for this.

Hi Sean,

Thanks for your information, the preview data work on first load, but I've a REST Api call with js after that, the data response is not correct, I've checked and saw it's can not get the correct mode in Preview mode, do you have any solution for this?

Thanks

In short, a REST API call does not have any inherent context about the page state or whether it is in preview mode.

The ContentRetriever does allow you to override the inferred preview state, enabling you to explicitly load preview content instead of live content. This could form part of your solution but you would need to ensure proper safeguards were in place such that preview content was never available outside of intended scenarios. The remaining challenge is determining when the API request should enable preview mode. While there are ways to attempt to infer this based on available parameters, these approaches tend to be brittle and can break down across different scenarios, so I would be cautious about relying on them.

One potential approach could be to output the required API URL directly on the page on load, allowing Xperience by Kentico’s middleware to append the necessary virtual context parameters to support preview mode. If you then consumed this URL, it would be used with the appended virtual context and may allow the server to infer the preview state of the request. This is not something I have tested, so it would need to be validated in practice.

Sean may be able to provide more definitive guidance here.

To response this discussion, you have to login first.