Preview mode does not work in Pages editor when fetching a custom API route in Next.js application


Description

A 404 Not Found error might occur when accessing a custom API route in a Next.js application using Pages editor and preview mode.
This issue arises due to a hostname mismatch, where the request is sent to the XM Cloud CM (Content Management) hostname instead of the editing host. The relative path specified relies on the current hostname, leading to the error.

Solution

To address the issue proceed as follows:

  1. Use an absolute path instead of a relative one when fetching data from your endpoint. This means specifying the complete URL (including the domain) rather than a path relative to the current page.
  2. Add the public URL (the base URL of your application) before the API route to ensure compatibility with Sitecore Experience Editor or Pages, for example:
    await fetch(publicUrl + "/api/customApiEndpoint");