Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft Mode Preview Not Working with New Implementation #8708

Closed
danielkoller opened this issue Oct 15, 2024 · 4 comments
Closed

Draft Mode Preview Not Working with New Implementation #8708

danielkoller opened this issue Oct 15, 2024 · 4 comments
Assignees

Comments

@danielkoller
Copy link

danielkoller commented Oct 15, 2024

Link to reproduction

No response

Environment Info

Payload: 3.0.0-beta.113
Node.js: v22.9.0
Next.js: 15.0.0-canary.173

Describe the Bug

Hello Payload CMS team,

I'm experiencing issues with the new draft mode preview implementation from the website template. The previous solution was working fine, but after updating to the new recommended approach, I can no longer access draft posts.

Previous working implementation:

import jwt from 'jsonwebtoken'
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import configPromise from '@payload-config'
const payloadToken = 'payload-token'
export async function GET(
req: Request & {
cookies: {
get: (name: string) => {
value: string
}
}
},
): Promise<Response> {
const payload = await getPayloadHMR({ config: configPromise })
const token = req.cookies.get(payloadToken)?.value
const { searchParams } = new URL(req.url)
const path = searchParams.get('path')
if (!path) {
return new Response('No path provided', { status: 404 })
}
if (!token) {
return new Response('You are not allowed to preview this page', { status: 403 })
}
let user
try {
user = jwt.verify(token, payload.secret)
} catch (error) {
payload.logger.error('Error verifying token for live preview:', error)
}
if (!user) {
await draftMode().disable()
return new Response('You are not allowed to preview this page', { status: 403 })
}
await draftMode().enable()
return redirect(path)
}

New implementation (not working):

import jwt from 'jsonwebtoken'
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import configPromise from '@payload-config'
import { CollectionSlug } from 'payload'
const payloadToken = 'payload-token'
export async function GET(
req: Request & {
cookies: {
get: (name: string) => {
value: string
}
}
},
): Promise<Response> {
const payload = await getPayloadHMR({ config: configPromise })
const token = req.cookies.get(payloadToken)?.value
const { searchParams } = new URL(req.url)
const path = searchParams.get('path')
const collection = searchParams.get('collection') as CollectionSlug
const slug = searchParams.get('slug')
const previewSecret = searchParams.get('previewSecret')
if (previewSecret) {
return new Response('You are not allowed to preview this page', { status: 403 })
} else {
if (!path) {
return new Response('No path provided', { status: 404 })
}
if (!collection) {
return new Response('No collection provided', { status: 404 })
}
if (!slug) {
return new Response('No slug provided', { status: 404 })
}
if (!token) {
return new Response('You are not allowed to preview this page', { status: 403 })
}
if (!path.startsWith('/')) {
return new Response('This endpoint can only be used for internal previews', { status: 500 })
}
let user
try {
user = jwt.verify(token, payload.secret)
} catch (error) {
payload.logger.error('Error verifying token for live preview:', error)
}
const draft = await draftMode()
if (!user) {
draft.disable()
return new Response('You are not allowed to preview this page', { status: 403 })
}
try {
const docs = await payload.find({
collection: collection,
where: {
slug: {
equals: slug,
},
},
})
if (!docs.docs.length) {
return new Response('Document not found', { status: 404 })
}
} catch (error) {
payload.logger.error('Error verifying token for live preview:', error)
}
draft.enable()
redirect(path)
}
}

With the new implementation, I can no longer access draft posts. The preview functionality doesn't work as expected, as the LivePreview is not loading and the Preview gives me "Document not found".

When the page or post is already published it is working perfectly fine, though. It routes to the correct slug and the LivePreview is also working flawlessly.

I've noticed that I have the next folder with the preview routes in the app folder and in the website template it is in the frontend folder. When I put it there for testing purposes, it completely broke the preview, as I wasnt able to even access live pages/posts anymore.

Reproduction Steps

Reproduction Steps:

  1. Setup:

    • Start with a fresh installation of Payload CMS with Next.js (version [15.0.0-canary.173]).
    • Ensure you have at least one collection (e.g., 'pages' or 'posts') configured.
  2. Implement the original (working) preview route:

    • Create a file app/next/preview/route.ts with the code from above (see first example)
  3. Test the original implementation:

    • Create a draft post/page in the Payload CMS admin panel.
    • Click the "Preview" button.
    • Verify that you can see the draft content in the preview.
  4. Update to the new (non-working) preview route:

    • Replace the content of app/next/preview/route.ts with the code from above (see second example)
  5. Update collection configuration:

    • In your collection config file (e.g., pages.ts or posts.ts), ensure the admin.preview function is set up correctly:
      admin: {
       preview: (data) => {
       const path = generatePreviewPath({
         slug: typeof data?.slug === 'string' ? data.slug : '',
         collection: 'pages',
       })
      
       return `${process.env.NEXT_PUBLIC_SERVER_URL}${path}`
  6. Test the new implementation:

    • Create a new draft post/page or edit an existing one in the Payload CMS admin panel.
    • Click the "Preview" button.
    • Observe that the preview fails to load the draft content.
  7. Check for errors:

    • Open your browser's developer tools.
    • Look for any error messages in the Console tab.
    • Check the Network tab for any failed requests related to the preview.
    • When visiting slug (http://localhost:3000/next/preview?slug=testartikel&collection=news&path=%2Fnews%2Ftestartikel) directly see the message: You are not allowed to preview this page.
    • See these errors in the console -> ERROR: Error verifying token for live preview:
      GET /next/preview?slug=testartikel&collection=news&path=%2Fnews%2Ftestartikel 403 in 925ms
  8. Additional tests:

    • Try previewing a published post/page to see if it works.
    • Attempt to access a draft post/page directly through the URL.

Expected result: The preview should successfully load draft content for authenticated users.

Actual result: The preview fails to load draft content, and draft posts/pages are inaccessible.

Adapters and Plugins

No response

@danielkoller danielkoller added status: needs-triage Possible bug which hasn't been reproduced yet v3 labels Oct 15, 2024
@paulpopus paulpopus self-assigned this Oct 15, 2024
@github-actions github-actions bot removed the status: needs-triage Possible bug which hasn't been reproduced yet label Oct 15, 2024
@paulpopus
Copy link
Contributor

Thanks for catching this, the fix here is to pass draft: true in the fetch happening inside /next/preview route.

See #8714 for the change

@danielkoller
Copy link
Author

Awesome. Thanks for the quick fix!

Copy link
Contributor

🚀 This is included in version v3.0.0-beta.115

Copy link
Contributor

This issue has been automatically locked.
Please open a new issue if this issue persists with any additional detail.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 18, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants