Next.js › Database Integration with Next.js
How would you handle a database write inside a server action while keeping the user interface responsive?
AdvancedAnswer
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.