Last active
August 24, 2024 21:34
-
-
Save pvaladez/897fe90a8bcecf7ae9479879c2524c56 to your computer and use it in GitHub Desktop.
Payload CMS revalidatePost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/payload/utilities/revalidate.ts | |
import type { Payload } from 'payload'; | |
export const revalidate = async (args: { | |
slug: string; | |
payload: Payload; | |
}): Promise<void> => { | |
const { payload, slug } = args; | |
try { | |
const res = await fetch( | |
`${process.env.NEXT_PUBLIC_FRONTEND_URL}/api/revalidate?secret=${process.env.NEXT_PRIVATE_REVALIDATION_KEY}&slug=${slug}`, | |
{ cache: 'no-cache' }, | |
); | |
if (res.ok) { | |
payload.logger.info(`Revalidated page '${slug}'`); | |
} else { | |
payload.logger.error( | |
`Error revalidating page '${slug}': ${JSON.stringify( | |
res, | |
)}`, | |
); | |
} | |
} catch (err: unknown) { | |
payload.logger.error( | |
`Error hitting revalidate route for page '${slug}': ${err}`, | |
); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/payload/collections/BlogPosts/hooks/revalidatePost.ts | |
import type { AfterChangeHook } from 'payload/dist/collections/config/types'; | |
import { revalidate } from '@/payload/utilities/revalidate'; | |
// Revalidate the post in the background, so the user doesn't have to wait | |
// Notice that the hook itself is not async and we are not awaiting `revalidate` | |
export const revalidatePost: AfterChangeHook = ({ doc, req: { payload } }) => { | |
revalidate({ payload, slug: `blog/${doc.id}` }); | |
// Revalidate the blog overview page | |
revalidate({ payload, slug: '[locale]/(default)/blog' }); | |
return doc; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment