typescriptintermediate
Server Action with Revalidation
Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.
typescriptPress ⌘/Ctrl + Shift + C to copy
'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.
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms
typescriptintermediate
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
#nextjs#server-actions
typescriptadvanced
Form with Server Action Validation
Build forms using Next.js server actions with server-side validation, error handling, and useActionState.
Best for: Contact form submissions
#nextjs#forms
typescriptbeginner
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
Best for: form submissions
#nextjs#server-actions