I have a next.js site deployed to Vercel, that fetches data from an API provided by Django. Next.js has this new feature (Incremental Static Regeneration On-Demand) where you can rebuild a specific page without need to rebuild the entire site with an url like this:
https://<my-site.com>/api/revalidate?secret=my-token
I need the next.js site rebuild some pages when the database changes, so it shows the new data, and i tried to make a request (with requests package) in the save method like this:
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs)
r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>")
It seems to work when i trigger that url from my browser, but it doesn't work when i trigger it from Django. The response of this Response object (r) is a 200 Status Code, as expected, with {"revalidated":true} (r.text), but it doesn't update the site anyways.
How can i implement this?
EDIT: here's the pages/api/revalidate.js code:
export default async function handler(req, res) {
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
return res.status(401).json({ message: 'Invalid token' })
}
try {
await res.unstable_revalidate('/')
await res.unstable_revalidate('/url')
return res.json({ revalidated: true })
} catch (err) {
return res.status(500).send('Error revalidating')
}
}
Had similar problem. I think it wasn't working because you actually need to save before revalidation.
This worked for me:
def save(self, *args, **kwargs):
try:
return super().save(*args, **kwargs)
finally:
r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>")