next
module with a preview.ts
file in my common
directory.
Useful utilities
These will be used for both enabling & disabling preview mode.Disable preview
?slug=xx
, otherwise just print that the preview mode has been disabled. You can customise that default case, going to the homepage is probably a good idea.
Enabling preview
This is where the magic happens. First define some types (if you’re not using TypeScript, you can leave these out, but they really help!)enablePreview
is a function that returns a function. We pass in the method to confirm the slugs exist and a redirectSlugFormatter
, this will be your chance to format the slug. For example, if someone wants /article/one
. Your CMS may only return the slug of one
, you can then pass in a method that appends the /article
to the slug before the user is redirected.
The endpoint will need to be passed 2 query strings.
secret
- to confirm only people you want are requesting the preview. This is stored in theDATO_PREVIEW_SECRET
environment variable.slug
- the page slug that you want to preview
Usage
Now that you have this, how do you use it? You’ll need to create at least 2 files.pages/api/disable-preview.ts
- disables the previewpages/api/preview.ts
- enables the preview
pages/api/disable-preview.ts
pages/api/preview.ts
pages/api/preview/article.ts
I hope this allows you to easily create your preview routes. Check out the Nextjs Documentation for more details around the subject, for example, checking the preview state in
getStaticProps
etc.