This is an alternative approach to doing previews of CMS content in Next.js. The canonical solution involves a special API route that sets a cookie in the editor‘s browser and then redirects it to the normal page URL. The page then picks up the cookie and switches to preview mode.
This didn’t quite sit right with me – I’d rather use a specific preview URL and not rely on cookies for determining the preview state. It seemed like it might lead to confusing situations. I couldn’t see any reason why they would implement it like that.
Then I realized that the benefit of this is that you get to reuse all the data fetching code in your page files, and avoid having to reimplement a special Preview version of each page.
I then thought about it some more and remembered that all of those pages have a uniform API for defining their data: getStaticProps() and getServerSideProps(). What if I could create ONE preview page and have it fetch each page’s data by simply calling these functions?
Turns out that I could. The only downside is that there is some maintenance involved with the preview page/route whenever you add or modify your page files.
The following is a simplified version of the preview page I built. Please share your thoughts!