Claude
Skills
Sign in
Back

nextjs-server-actions

Included with Lifetime
$97 forever

Complete Next.js Server Actions system (Next.js 15.5/16). PROACTIVELY activate for: (1) Defining Server Actions with 'use server', (2) Form handling with actions, (3) useActionState for form state, (4) useFormStatus for pending states, (5) Optimistic updates with useOptimistic, (6) Validation with Zod and next-safe-action, (7) Authorization in actions, (8) File uploads, (9) Revalidation after mutations, (10) Type-safe actions with next-safe-action library. Provides: Action patterns, form integration, validation, optimistic UI, error handling, next-safe-action integration. Ensures secure server mutations with proper validation and UX.

Design

What this skill does


## Quick Reference

| Pattern | Code | Purpose |
|---------|------|---------|
| Inline action | `async function action() { 'use server'; }` | Define in component |
| Actions file | `'use server'` at file top | Dedicated actions file |
| Form action | `<form action={serverAction}>` | Native form integration |
| Bind args | `action.bind(null, id)` | Pass additional args |

| Hook | Import | Purpose |
|------|--------|---------|
| `useActionState` | `react` | Form state + pending |
| `useFormStatus` | `react-dom` | Pending state in children |
| `useOptimistic` | `react` | Optimistic UI updates |

| Revalidation | Function | Scope |
|--------------|----------|-------|
| `revalidatePath('/posts')` | Path-based | Specific route |
| `revalidateTag('posts')` | Tag-based | All tagged fetches |
| `redirect('/success')` | Navigation | After mutation |

## When to Use This Skill

Use for **server-side mutations**:
- Form submissions without API routes
- Database mutations (create, update, delete)
- File uploads to server
- Implementing optimistic updates
- Form validation with error display

**Related skills:**
- For data fetching: see `nextjs-data-fetching`
- For caching/revalidation: see `nextjs-caching`
- For authentication in actions: see `nextjs-authentication`

---

# Next.js Server Actions

## Defining Server Actions

### Inline Server Action

```tsx
// app/posts/page.tsx
export default function PostsPage() {
  async function createPost(formData: FormData) {
    'use server';

    const title = formData.get('title') as string;
    const content = formData.get('content') as string;

    await db.posts.create({
      data: { title, content },
    });

    revalidatePath('/posts');
  }

  return (
    <form action={createPost}>
      <input name="title" placeholder="Title" required />
      <textarea name="content" placeholder="Content" required />
      <button type="submit">Create Post</button>
    </form>
  );
}
```

### Separate Actions File

```tsx
// app/actions.ts
'use server';

import { revalidatePath, revalidateTag } 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(1, 'Content is required'),
});

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

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
    };
  }

  try {
    await db.posts.create({
      data: validatedFields.data,
    });
  } catch (error) {
    return { error: 'Failed to create post' };
  }

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

export async function deletePost(id: string) {
  await db.posts.delete({ where: { id } });
  revalidateTag('posts');
}

export async function updatePost(id: string, formData: FormData) {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;

  await db.posts.update({
    where: { id },
    data: { title, content },
  });

  revalidatePath(`/posts/${id}`);
  return { success: true };
}
```

## Using Server Actions in Forms

### Basic Form

```tsx
// app/contact/page.tsx
import { submitContact } from './actions';

export default function ContactPage() {
  return (
    <form action={submitContact}>
      <input name="name" placeholder="Name" required />
      <input name="email" type="email" placeholder="Email" required />
      <textarea name="message" placeholder="Message" required />
      <button type="submit">Send</button>
    </form>
  );
}
```

### Form with useActionState

```tsx
// app/signup/page.tsx
'use client';

import { useActionState } from 'react';
import { signup } from './actions';

const initialState = {
  errors: {} as Record<string, string[]>,
  message: '',
};

export default function SignupPage() {
  const [state, formAction, isPending] = useActionState(signup, initialState);

  return (
    <form action={formAction}>
      <div>
        <input name="email" type="email" placeholder="Email" />
        {state.errors?.email && (
          <p className="error">{state.errors.email[0]}</p>
        )}
      </div>

      <div>
        <input name="password" type="password" placeholder="Password" />
        {state.errors?.password && (
          <p className="error">{state.errors.password[0]}</p>
        )}
      </div>

      {state.message && <p className="message">{state.message}</p>}

      <button type="submit" disabled={isPending}>
        {isPending ? 'Signing up...' : 'Sign Up'}
      </button>
    </form>
  );
}
```

```tsx
// app/signup/actions.ts
'use server';

import { z } from 'zod';

const SignupSchema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
});

export async function signup(prevState: any, formData: FormData) {
  const validatedFields = SignupSchema.safeParse({
    email: formData.get('email'),
    password: formData.get('password'),
  });

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: '',
    };
  }

  try {
    await createUser(validatedFields.data);
    return { errors: {}, message: 'Account created successfully!' };
  } catch (error) {
    return { errors: {}, message: 'Failed to create account' };
  }
}
```

### useFormStatus for Pending State

```tsx
// components/SubmitButton.tsx
'use client';

import { useFormStatus } from 'react-dom';

export function SubmitButton({ children }: { children: React.ReactNode }) {
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Submitting...' : children}
    </button>
  );
}
```

```tsx
// Usage in form
import { SubmitButton } from '@/components/SubmitButton';

export default function Form() {
  return (
    <form action={submitForm}>
      <input name="title" />
      <SubmitButton>Submit</SubmitButton>
    </form>
  );
}
```

## Optimistic Updates

### useOptimistic Hook

```tsx
// app/posts/[id]/comments.tsx
'use client';

import { useOptimistic, useTransition } from 'react';
import { addComment } from './actions';

interface Comment {
  id: string;
  text: string;
  pending?: boolean;
}

export function Comments({ initialComments }: { initialComments: Comment[] }) {
  const [isPending, startTransition] = useTransition();
  const [optimisticComments, addOptimisticComment] = useOptimistic(
    initialComments,
    (state, newComment: Comment) => [...state, { ...newComment, pending: true }]
  );

  async function handleSubmit(formData: FormData) {
    const text = formData.get('text') as string;

    startTransition(async () => {
      addOptimisticComment({
        id: `temp-${Date.now()}`,
        text,
      });

      await addComment(formData);
    });
  }

  return (
    <div>
      <ul>
        {optimisticComments.map((comment) => (
          <li
            key={comment.id}
            style={{ opacity: comment.pending ? 0.5 : 1 }}
          >
            {comment.text}
            {comment.pending && ' (posting...)'}
          </li>
        ))}
      </ul>

      <form action={handleSubmit}>
        <input name="text" placeholder="Add comment" required />
        <button type="submit" disabled={isPending}>
          Add
        </button>
      </form>
    </div>
  );
}
```

### Optimistic Like Button

```tsx
// components/LikeButton.tsx
'use client';

import { useOptimistic, useTransition } from 'react';
import { toggleLike } from '@/app/actions';

interface LikeButtonProps {
  postId: string;
  initialLiked: boolean;
  initialCount: number;
}

export function LikeButton({
  postId,
  initialLiked,
  initialCount,
}: LikeButtonProps) {
  const [isPending, startTransition] = useTransition();
  const [optimistic, setOptimistic] = useOptimistic(
    { liked: init

Related in Design