JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
senior
server-actions

What are Server Actions in Next.js and how do they handle form submissions and mutations?

nextjs
server-actions
forms
mutations
progressive-enhancement
react
useFormState
Quick Answer

Server Actions are async functions that execute on the server, marked with 'use server'. They enable secure data mutations directly from components without creating API routes, support progressive enhancement (forms work without JavaScript), and integrate seamlessly with React's form handling and optimistic updates.

Detailed Explanation

What Are Server Actions?

Server Actions are async functions that run exclusively on the server. They:

  1. Replace API Routes for Mutations: No need for POST /api/submit - call functions directly
  2. Work with Progressive Enhancement: Forms submit and work even with JS disabled
  3. Integrate with React: Work with useFormState, useFormStatus, and useOptimistic
  4. Are Secure by Default: Code never ships to client, secrets stay safe

Defining Server Actions

// Option 1: 'use server' at top of file (all exports are actions)
'use server';
export async function createPost(formData: FormData) { ... }

// Option 2: Inline in Server Component
async function Page() {
  async function handleSubmit(formData: FormData) {
    'use server';
    // This runs on server
  }
}

Key Features

Form Integration

  • Pass Server Action to <form action={...}>
  • Access form data via FormData parameter
  • Forms work without JavaScript (progressive enhancement)

Validation

  • Use Zod or similar for input validation
  • Return validation errors to display in UI
  • Never trust client input - always validate on server

Revalidation

  • Call revalidatePath() to refresh cached pages
  • Use revalidateTag() for fine-grained cache control
  • Data updates reflect immediately after mutation

Optimistic Updates

  • Use useOptimistic for instant UI feedback
  • Roll back automatically on server error
  • Combine with useFormStatus for loading states

When to Use Server Actions

  • Form submissions (contact, signup, checkout)
  • Data mutations (create, update, delete)
  • Database operations (directly call Prisma, Drizzle)
  • File uploads (with FormData)
  • Authentication (login, logout actions)

When NOT to Use

  • Data fetching - Use Server Components or route handlers
  • Third-party integrations needing specific HTTP methods
  • Webhooks - Use route handlers for incoming requests

Code Examples

Basic Server Action with Form
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';

const PostSchema = z.object({
  title: z.string().min(1, 'Title is required').max(100),
  content: z.string().min(10, 'Content must be at least 10 characters'),
});

export async function createPost(prevState: any, formData: FormData) {
  // Validate input
  const validatedFields = PostSchema.safeParse({
    title: formData.get('title'),
    content: formData.get('content'),
  });

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: 'Invalid fields. Failed to create post.',
    };
  }

  // Insert into database
  try {
    await db.post.create({ data: validatedFields.data });
  } catch (error) {
    return { message: 'Database error: Failed to create post.' };
  }

  // Revalidate and redirect
  revalidatePath('/posts');
  redirect('/posts');
}

Resources

Server Actions and Mutations - Next.js Docs

docs

Forms and Mutations - Next.js Learn

docs

Related Questions

How do API routes work in Next.js?

mid
api

What is the difference between controlled and uncontrolled components in React forms?

mid
forms
Previous
Explain the different rendering strategies in Next.js (SSR, SSG, ISR) and when to use each approach.
Next
How does Middleware work in Next.js and what are common use cases?