Server Action with Revalidation
Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.
'use server';
import { revalidatePath, revalidateTag } from 'next/cache';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const body = formData.get('body') as string;
if (!title?.trim() || !body?.trim()) {
return { error: 'Title and body are required' };
}
// await db.post.create({ data: { title, body } });
// Revalidate the posts listing page
revalidatePath('/posts');
// Or revalidate by cache tag
revalidateTag('posts');
return { success: true };
}
// Usage in a Client Component:
// <form action={createPost}>
// <input name="title" />
// <textarea name="body" />
// <button type="submit">Publish</button>
// </form>Use Cases
- Form submissions
- Like/bookmark actions
- Content publishing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
On-Demand ISR Revalidation
Trigger incremental static regeneration via API route with secret token validation for instant cache purge.
Cached Fetch with Revalidation
Fetch external data in Server Components with time-based revalidation and error boundaries.
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.