Overriding the preview feature in Umbraco

When building a headless solution your Umbraco installation might serve as an API and does not have any frontend attached to it. In those cases the default preview feature in Umbraco could become useless.

You might become tempted to remove or disable the preview feature in Umbraco in this kind of setup, but there is a workaround you can use to enable preview in a headless solution.

Stealing Umbraco's preview endpoint
When you click on the preview link in Umbraco backoffice, Umbraco will redirect you to /umbraco/preview?id={id}.

So what you can do is you can create your own preview controller by creating an UmbracoApiController:

By default UmbracoApiController’s will automatically map endpoints in the /Umbraco/Api/{YourController}/{YourAction} format.

But by enabling attribute routing you can use [Route] and [RoutePrefix] attributes to set whatever endpoint you like for your UmbracoApiController and this way you can "steal" Umbraco's default preview link:

This above snippet will work, but you will experience a quick little glitch when loading the page. This is because Umbraco will first call /umbraco/preview?init=true, probably since Umbraco renders a preview wrapper around the preview page. So you need to make sure that this endpoint works by checking if init is true and return a status 200 OK result:

Example:
In this example the editor is redirected to a /preview endpoint on our frontend application and the id parameter is forwarded to the frontend application. This could look something like this:

Later this frontend application will call our API with a preview flag and the latest content will be fetched from the database (instead of the published content cache) and returned as JSON.

I might share our headless setup in a future blog post but for the sake of keeping this post short and on the sole topic of overriding the preview endpoint, I’ll leave it for todays post.

But now you know how to steal the Umbraco preview feature, hope you find it useful. Take care of each other!

Cheers friends! ❤️