// simple example for testing it manually from your browser.exportdefaultfunctionhandler(req, res) {res.setPreviewData({})res.end('Preview mode enabled')}
exportdefaultasync (req, res) => {// Check the secret and next parameters// This secret should only be known to this API route and the CMSif (req.query.secret !=='MY_SECRET_TOKEN'||!req.query.slug) {returnres.status(401).json({ message:'Invalid token' }) }// Fetch the headless CMS to check if the provided `slug` exists// getPostBySlug would implement the required fetching logic to the headless CMSconstpost=awaitgetPostBySlug(req.query.slug)// If the slug doesn't exist prevent preview mode from being enabledif (!post) {returnres.status(401).json({ message:'Invalid slug' }) }// Enable Preview Mode by setting the cookiesres.setPreviewData({})// Redirect to the path from the fetched post// We don't redirect to req.query.slug as that might lead to open redirect vulnerabilitiesres.redirect(post.slug)}
exportasyncfunctiongetStaticProps(context) {// If you request this page with the preview mode cookies set://// - context.preview will be true// - context.previewData will be the same as// the argument used for `setPreviewData`.}
我們在預覽 API 路由中使用了 res.setPreviewData({}),因此 context.previewData 將會是 {}。如有需要,您可以使用它將工作階段資訊從預覽 API 路由傳遞至 getStaticProps。
例如,您的 headless CMS 可能會有不同的 API 端點用於草稿文章。如果是這樣,您可以使用 context.preview 來修改 API 端點網址,如下所示
exportasyncfunctiongetStaticProps(context) {// If context.preview is true, append "/preview" to the API endpoint// to request draft data instead of published data. This will vary// based on which headless CMS you're using.constres=awaitfetch(`https://.../${context.preview ?'preview':''}`)// ...}
這樣就完成了!如果您從 headless CMS 或手動存取預覽 API 路由(使用 secret 和 slug),您現在應該可以看到預覽內容。而且,如果您更新草稿而沒有發佈,您應該能夠預覽草稿。