📝 Next.js Handbook

Mutations

Advantages of using Server Actions for data mutations:

No API endpoints

Server Actions allow you to run asynchronous code directly on the server, eliminating the need for API endpoints to mutate data.

Progressive enhancement

Invoking a Server Action within a Server Component allows forms to work even if JavaScript has not yet loaded on the client.

Caching

Server Actions are deeply integrated with Next.js caching.

Revalidations

When a form is submitted through a Server Action, you can also revalidate the associated cache using APIs like revalidatePath and revalidateTag.

📋 Examples

The examples below help us understand situations where not revalidating the cache on-demand would lead to undesired effects. Imagine that a user wants to remain on the same page after updating a form. We would expect that the new data would immediately be displayed after submitting the form. That is what happens in example 1, but not in example 2.

Example 1
With cache revalidation on-demand

Please update the value and submit.

Behind the scenes, a server action that updates the data and revalidates the path will be invoked.

Cached data will be purged and the UI is updated with fresh data.

💡 Notice that the value you submitted is immediately displayed in the card below the form, as expected.

Update Form 1

Example 2
No cache revalidation on-demand

Please update the value and submit.

Behind the scenes, a server action that only updates the data will be invoked.

Since no revalidation was triggered, the old cached data will keep showing in the UI.

💡 Notice that if we refresh the page, or even press the submit button on the form 1 (which revalidates the whole path), we would then see the updated data.

Update Form 2