typescriptintermediate

Server Action with Revalidation

Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.

typescript
'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.