Next.js revalidatePath
A saved book does not show in the list until the list is refreshed. revalidatePath refreshes it.
The refresh line in the action
The action saves the book, refreshes the list path, and answers. The refresh is one line.
const saved = await addBookToStore({ ...parsed.data, read: false });
revalidatePath("/books");
return { ok: true, message: `Saved "${saved.title}" by ${saved.author}.` };The new book is in the list
The check counts the new title in the list page. One means it is there.
curl -s http://localhost:3112/books | grep -c 'The Left Hand of Darkness'Example
curl -s http://localhost:3112/books | grep -o 'The Left Hand of Darkness'Key points
- Stale: an old copy of a page, shown after the data behind it changed
- The list page reads the store once per visit. A new book lands after that read.
- revalidatePath tells Next.js to refresh a path. The next visit re-reads the store.
- One line in the action refreshes /books after the save.
- The new book then shows in the list. The old list is gone.
In this example, the check reads the list page after the new book was added. The title The Left Hand of Darkness is in the list, so the page re-read the store. Without the refresh, the list would still show the old three books. After the book was deleted, the same check found nothing, so the list follows the store both ways.
Note
The refresh line sits in the action, which curl could not drive here. The re-read itself is verified.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does revalidatePath("/books") do?