I have a blog post edit page on my Next.js project.
My post pages are using the Incremental Static Regeneration feature with a revalidate: 1 second (currently for testing). I'll later be using something like revalidate: 300 (5 minutes).
To update a post, this is what I do:
As an admin, I visit /admin/post/edit/my-post-slug, change whatever I need and save.
After saving, I'm doing a route.push to the post page, to see the new version in /post/my-post-slug.
Here is the code:
const savePost = async (post: BlogPost, router: NextRouter) => {
await savePostAPI(post);
cons POST_ROUTE = "/post/my-post-slug";
router.push(POST_ROUTE);
};
It's all working as intended, with one little caveat.
This is the flow I'm getting:
- I'M ON ADMIN POST EDIT PAGE AND I SAVE
- I GO TO POST PAGE VIA router.push() AND I SEE THE OLD CONTENT (THIS IS EXPECTED)
- WAIT A LITLE
- I HIT REFRESH (F5) ONCE AND I RELOAD THE PAGE AND STILL SEE OLD CONTENT (NOT EXPECTED)
- WAIT A LITLE
- I HIT REFRESH (F5) AGAIN AND SEE THE NEW CONTENT
I'm okay with seeing the old content after router.push(). Next.js is supposed to always serve cached content, even a stale one, before regenerating the new version. But why don't I see the new content right after pressing F5 for the first time? Why do I need to refresh it twice to see the new content? Doesn't router.push trigger a new server request and let the server know that it should regenerate the page (given the fact that is obviously stale, since revalidate:1 will make it stale after 1 second)? Why is that happening?
Instead of using router.push() should I just use window.location.href = "https://www.example.com/post/my-post-slug" to make sure I'll send that request that will trigger the regeneration of the page?
After further investigation, I can confirm.
router.push() implements a client-side transition, and that does not trigger a new getStaticProps call. It only fetches a JSON object with previously generated page props.
I.e: This means that the page will not be revalidated no matter how my client-side transitions you perform.
Either get the fresh data using client-side code, or do a full page reload from time to time. At least 2 will be necessary. The first one will return stale data and will trigger the revalidation process. The 2nd one will get the fresh data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With