Skip to content

Instantly share code, notes, and snippets.

@elliott-w
Last active November 30, 2025 21:10
Show Gist options
  • Select an option

  • Save elliott-w/0c93db8b6018752717b925e80ab08b9c to your computer and use it in GitHub Desktop.

Select an option

Save elliott-w/0c93db8b6018752717b925e80ab08b9c to your computer and use it in GitHub Desktop.
A better way to fetch drafts in nextjs that automatically handles draft and status args
import config from '@payload-config'
import { draftMode } from 'next/headers'
import { getPayload as getPayloadFn, type CollectionSlug } from 'payload'
declare module 'payload' {
interface BasePayload {
draftModifications?: boolean
}
}
export const getPayload = async () => {
const payload = await getPayloadFn({ config, key: 'frontend' })
if (!payload.draftModifications) {
payload.draftModifications = true
const methodsToOverride = [
'find',
'findGlobal',
'findVersions',
'findByID',
'findVersionByID',
'findGlobalVersionByID',
] as const
methodsToOverride.forEach((methodName) => {
const original = (payload[methodName] as any).bind(payload)
// Store the original method
;(payload as any)[methodName] = async (options: any) => {
const { isEnabled: isDraftMode } = await draftMode()
const byID = methodName.endsWith('ByID')
const isGlobal = methodName.includes('Global')
const draftsEnabled = Boolean(
isGlobal
? payload.globals.config.find(
(global) => global.slug === options.slug
)?.versions?.drafts
: payload.collections[options.collection as CollectionSlug].config
.versions.drafts
)
const newOptions =
draftsEnabled && typeof options.draft === 'undefined'
? {
...options,
draft: isDraftMode,
...(!byID && {
where: {
...(options.where || {}),
...(!isDraftMode && { _status: { equals: 'published' } }),
},
}),
}
: options
return original(newOptions)
}
})
}
return payload
}
export const getPayloadWithoutDraftMode = async () => {
const payload = await getPayloadFn({ config })
return payload
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment