Back to results for “Server Actions & Data Mutations”
Next.js › Database Integration with Next.js

How would you handle a database write inside a server action while keeping the user interface responsive?

Advanced

Answer

You perform the database update inside the server action itself, and after it completes, call revalidatePath or revalidateTag to refresh any cached pages that display that data, while also considering optimistic updates on the client so the interface feels instant even while the write is happening.
'use server';
import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';

export async function addComment(postId, text) {
  await db.comment.create({ data: { postId, text } });
  revalidatePath(`/posts/${postId}`);
}
Real-world example A comment form on a blog calls a server action to save a new comment to the database, then automatically refreshes the post page so the new comment appears without a manual page reload.

Common follow-ups: What is an optimistic update and how does it improve perceived performance?;How do you handle errors that occur during a database write inside a server action?