Skip to content
This repository was archived by the owner on Feb 27, 2024. It is now read-only.

Commit 03822e7

Browse files
committed
add on demand revalidation
1 parent 53c8488 commit 03822e7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

pages/api/wordpress/revalidate.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* On-demand post revalidation.
3+
*
4+
* @see https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#using-on-demand-revalidation
5+
* @author WebDevStudios
6+
* @param {object} req Instance of http.IncomingMessage.
7+
* @param {object} res Instance of http.ServerResponse.
8+
*/
9+
export default async function revalidate(req, res) {
10+
// Check for a valid secret.
11+
if (req.body.secret !== process.env.WORDPRESS_PREVIEW_SECRET) {
12+
return res.status(401).json({
13+
message:
14+
'Invalid secret. Please check your .env file or the POST request.'
15+
})
16+
}
17+
18+
// Check for a valid post slug.
19+
if (!req.body.slug) {
20+
return res.status(400).json({
21+
message: 'A slug is required to revalidate the cache.'
22+
})
23+
}
24+
25+
// Try to revalidate the post cache.
26+
try {
27+
await res.unstable_revalidate(req.body.slug)
28+
return res.status(200).json({
29+
message: `Success! The cache for ${req.body.slug} was successfully revalidated.`
30+
})
31+
} catch (err) {
32+
return res.status(500).json({
33+
message: err.message
34+
})
35+
}
36+
}

0 commit comments

Comments
 (0)