server-actions

This skill should be used when the user asks about "Server Actions", "form handling in Next.js", "mutations", "useFormState", "useFormStatus", "revalidatePath", "revalidateTag", or needs guidance on data mutations and form submissions in Next.js App Router.

2,707 stars

Best use case

server-actions is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

This skill should be used when the user asks about "Server Actions", "form handling in Next.js", "mutations", "useFormState", "useFormStatus", "revalidatePath", "revalidateTag", or needs guidance on data mutations and form submissions in Next.js App Router.

Teams using server-actions should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/server-actions/SKILL.md --create-dirs "https://raw.githubusercontent.com/davepoon/buildwithclaude/main/plugins/nextjs-expert/skills/server-actions/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/server-actions/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How server-actions Compares

Feature / Agentserver-actionsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

This skill should be used when the user asks about "Server Actions", "form handling in Next.js", "mutations", "useFormState", "useFormStatus", "revalidatePath", "revalidateTag", or needs guidance on data mutations and form submissions in Next.js App Router.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Next.js Server Actions

## Overview

Server Actions are asynchronous functions that execute on the server. They can be called from Client and Server Components for data mutations, form submissions, and other server-side operations.

## Defining Server Actions

### In Server Components

Use the `'use server'` directive inside an async function:

```tsx
// app/page.tsx (Server Component)
export default function Page() {
  async function createPost(formData: FormData) {
    'use server'
    const title = formData.get('title') as string
    await db.post.create({ data: { title } })
  }

  return (
    <form action={createPost}>
      <input name="title" />
      <button type="submit">Create</button>
    </form>
  )
}
```

### In Separate Files

Mark the entire file with `'use server'`:

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

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string
  await db.post.create({ data: { title } })
}

export async function deletePost(id: string) {
  await db.post.delete({ where: { id } })
}
```

## Form Handling

### Basic Form

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

export async function submitContact(formData: FormData) {
  const name = formData.get('name') as string
  const email = formData.get('email') as string
  const message = formData.get('message') as string

  await db.contact.create({
    data: { name, email, message }
  })
}

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

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

### With Validation (Zod)

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

import { z } from 'zod'

const schema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
})

export async function signup(formData: FormData) {
  const parsed = schema.safeParse({
    email: formData.get('email'),
    password: formData.get('password'),
  })

  if (!parsed.success) {
    return { error: parsed.error.flatten() }
  }

  await createUser(parsed.data)
  return { success: true }
}
```

## useFormState Hook

Handle form state and errors:

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

import { useFormState } from 'react-dom'
import { signup } from '@/app/actions'

const initialState = {
  error: null,
  success: false,
}

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

  return (
    <form action={formAction}>
      <input name="email" type="email" />
      <input name="password" type="password" />
      {state.error && (
        <p className="text-red-500">{state.error}</p>
      )}
      <button type="submit">Sign Up</button>
    </form>
  )
}

// app/actions.ts
'use server'

export async function signup(prevState: any, formData: FormData) {
  const email = formData.get('email') as string

  if (!email.includes('@')) {
    return { error: 'Invalid email', success: false }
  }

  await createUser({ email })
  return { error: null, success: true }
}
```

## useFormStatus Hook

Show loading states during submission:

```tsx
// components/submit-button.tsx
'use client'

import { useFormStatus } from 'react-dom'

export function SubmitButton() {
  const { pending } = useFormStatus()

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

// Usage in form
import { SubmitButton } from '@/components/submit-button'

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

## Revalidation

### revalidatePath

Revalidate a specific path:

```tsx
'use server'

import { revalidatePath } from 'next/cache'

export async function createPost(formData: FormData) {
  await db.post.create({ data: { ... } })

  // Revalidate the posts list page
  revalidatePath('/posts')

  // Revalidate a dynamic route
  revalidatePath('/posts/[slug]', 'page')

  // Revalidate all paths under /posts
  revalidatePath('/posts', 'layout')
}
```

### revalidateTag

Revalidate by cache tag:

```tsx
// Fetching with tags
const posts = await fetch('https://api.example.com/posts', {
  next: { tags: ['posts'] }
})

// Server Action
'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(formData: FormData) {
  await db.post.create({ data: { ... } })
  revalidateTag('posts')
}
```

## Redirects After Actions

```tsx
'use server'

import { redirect } from 'next/navigation'

export async function createPost(formData: FormData) {
  const post = await db.post.create({ data: { ... } })

  // Redirect to the new post
  redirect(`/posts/${post.slug}`)
}
```

## Optimistic Updates

Update UI immediately while action completes:

```tsx
'use client'

import { useOptimistic } from 'react'
import { addTodo } from '@/app/actions'

export function TodoList({ todos }: { todos: Todo[] }) {
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(
    todos,
    (state, newTodo: string) => [
      ...state,
      { id: 'temp', title: newTodo, completed: false }
    ]
  )

  async function handleSubmit(formData: FormData) {
    const title = formData.get('title') as string
    addOptimisticTodo(title) // Update UI immediately
    await addTodo(formData)  // Server action
  }

  return (
    <>
      <form action={handleSubmit}>
        <input name="title" />
        <button>Add</button>
      </form>
      <ul>
        {optimisticTodos.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </>
  )
}
```

## Non-Form Usage

Call Server Actions programmatically:

```tsx
'use client'

import { deletePost } from '@/app/actions'

export function DeleteButton({ id }: { id: string }) {
  return (
    <button onClick={() => deletePost(id)}>
      Delete
    </button>
  )
}
```

## Error Handling

```tsx
'use server'

export async function createPost(formData: FormData) {
  try {
    await db.post.create({ data: { ... } })
    return { success: true }
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError) {
      if (error.code === 'P2002') {
        return { error: 'A post with this title already exists' }
      }
    }
    return { error: 'Failed to create post' }
  }
}
```

## Security Considerations

1. **Always validate input** - Never trust client data
2. **Check authentication** - Verify user is authorized
3. **Use CSRF protection** - Built-in with Server Actions
4. **Sanitize output** - Prevent XSS attacks

```tsx
'use server'

import { auth } from '@/lib/auth'

export async function deletePost(id: string) {
  const session = await auth()

  if (!session) {
    throw new Error('Unauthorized')
  }

  const post = await db.post.findUnique({ where: { id } })

  if (post.authorId !== session.user.id) {
    throw new Error('Forbidden')
  }

  await db.post.delete({ where: { id } })
}
```

## Resources

For detailed patterns, see:
- `references/form-handling.md` - Advanced form patterns
- `references/revalidation.md` - Cache revalidation strategies
- `examples/mutation-patterns.md` - Complete mutation examples

Related Skills

server-components

2707
from davepoon/buildwithclaude

This skill should be used when the user asks about "Server Components", "Client Components", "'use client' directive", "when to use server vs client", "RSC patterns", "component composition", "data fetching in components", or needs guidance on React Server Components architecture in Next.js.

soft-screening-startup

2707
from davepoon/buildwithclaude

Activate for ANY startup evaluation, investment screening, or company assessment. Triggers include: "evaluate this startup", "screen this company", "should I invest in X", "is this a good investment", "what do you think about this company", "review this startup", "score this company", "rate this pitch", "assess this founder", "quick take on X", "is X worth investing in", "pass or decline on X", "what's your verdict on X", "first look at this company", "quick screen on X", "what's your take on this founder", "is this fundable", "would a VC invest in this". Also triggers when a user pastes a company description, funding ask, or founder background and asks for an opinion. Works on claude.ai and Claude Code. For hard-mode deterministic scoring with Python audit trail, use /venture-capital-intelligence:hard-screening-startup.

market-size

2707
from davepoon/buildwithclaude

Run TAM/SAM/SOM market sizing with top-down and bottom-up methods, competitive landscape, and tech stack analysis. Triggered by: "/venture-capital-intelligence:market-size", "size this market", "what is the TAM for X", "market sizing analysis", "competitive landscape for X", "who are the competitors", "TAM SAM SOM for X", "market opportunity analysis", "how big is this market", "is this market big enough", "what's the addressable market", "total addressable market for X", "how large is the opportunity", "market research for X", "how saturated is this market", "market size estimate", "go-to-market sizing", "what is the serviceable market". Claude Code only. Requires Python 3.x. Uses web search for market data.

hard-screening-startup

2707
from davepoon/buildwithclaude

Deterministic Python-scored startup screening with full audit trail. Use when you need a reproducible, weighted-score verdict on a startup — not just a qualitative opinion. Triggered by: "/venture-capital-intelligence:hard-screening-startup", "hard screen this startup", "run a hard screen on X", "score this startup with Python", "give me an auditable screen", "run a scored evaluation on X", "give me a weighted score for this startup", "screen with numbers", "objective startup score", "reproducible screen", "investment scorecard for X", "score this company out of 100", "run the full screen on X". Claude Code only. Requires Python 3.x. For conversational soft-mode screening, use /venture-capital-intelligence:soft-screening-startup.

fund-operations

2707
from davepoon/buildwithclaude

Compute fund KPIs (TVPI, DPI, IRR, MOIC), model carried interest and management fees, and generate LP quarterly update narratives. Triggered by: "/venture-capital-intelligence:fund-operations", "calculate fund KPIs", "what is my fund TVPI", "IRR calculation", "compute MOIC", "LP report", "quarterly update draft", "carried interest calculation", "management fee calculation", "fund performance report", "write my LP update", "how is my fund performing", "what is my DPI", "fund returns analysis", "model my carry", "how much carry do I earn", "portfolio performance summary", "generate investor update". Claude Code only. Requires Python 3.x.

financial-model

2707
from davepoon/buildwithclaude

Run deterministic financial models for startup valuation and SaaS health analysis. Triggered by: "/venture-capital-intelligence:financial-model", "run a financial model on X", "DCF this company", "model the financials", "calculate runway", "what is the valuation", "SaaS metrics model", "LTV CAC analysis", "unit economics", "burn rate analysis", "comparable valuation", "how long is my runway", "what's my burn multiple", "revenue projection for X", "model the ARR growth", "what is the pre-money valuation", "comps analysis", "NRR and churn model", "how healthy are these SaaS metrics". Claude Code only. Requires Python 3.x. Accepts user-supplied numbers or searches for publicly available data.

explain-equity-terms

2707
from davepoon/buildwithclaude

Activate for ANY equity, legal, or term sheet question related to startup investing or fundraising. Triggers include: "what is a SAFE", "explain this term sheet", "what does pro-rata mean", "what is liquidation preference", "explain anti-dilution", "ISO vs NSO", "what is a 83(b) election", "what is carried interest", "explain drag-along", "what is a valuation cap", "what does MFN mean", "explain convertible note vs SAFE", "what is a down round", "explain vesting cliff", "what does fully diluted mean", "term sheet question", "equity question", "what does this clause mean". Also triggers when a user pastes legal text from a term sheet, SAFE, or subscription agreement and asks what it means. Works on claude.ai and Claude Code.

deal-sourcing-signals

2707
from davepoon/buildwithclaude

Scan a company or sector for deal-sourcing signals across 6 dimensions. Triggered by: "/venture-capital-intelligence:deal-sourcing-signals", "scan signals for X", "what signals is X showing", "deal sourcing scan", "hiring signals for X", "is X raising soon", "monitor this company", "company signal scan", "sourcing brief for X", "what is X up to", "is X growing", "track this company", "deal signal report for X", "is this company fundraising", "what are the momentum signals for X", "find signals on X", "is X worth tracking". Claude Code only. Requires Python 3.x. Uses web search for live signal data.

cap-table-waterfall

2707
from davepoon/buildwithclaude

Model cap table dilution, SAFE conversion, and exit waterfall across scenarios. Triggered by: "/venture-capital-intelligence:cap-table-waterfall", "model my cap table", "simulate dilution", "SAFE conversion math", "exit waterfall", "how much do I own after Series A", "liquidation waterfall", "cap table scenario", "what happens to equity at exit", "model the waterfall", "how much equity do I have left", "what is my ownership after funding", "run dilution scenarios", "model a new round", "what happens at acquisition", "cap table after SAFE conversion", "pari passu waterfall", "preference stack analysis". Claude Code only. Requires Python 3.x.

analyze-pitch-deck

2707
from davepoon/buildwithclaude

Activate for ANY pitch deck analysis, feedback, or review request. Triggers include: "analyze this deck", "review my pitch deck", "critique my pitch", "feedback on my slides", "is my deck investor ready", "what's wrong with my pitch", "how would a VC react to this deck", "score my pitch deck", "rate my slides", "improve my deck", "what slides am I missing", "is this pitch compelling". Also triggers when a user pastes slide content, describes their deck structure, or shares a company narrative and asks for investor feedback. Works on claude.ai and Claude Code.

public-plugin-builder

2707
from davepoon/buildwithclaude

Activate when the user wants to build a Claude plugin, create a Claude skill, make a Claude agent, structure a Claude Code plugin, says "build a plugin", "create a skill", "new claude skill", "new agent", "help me make a plugin", "plugin builder", "claude plugin helper", "how do I build a Claude skill", "I want to create a Claude plugin", "plugin building", or asks how to structure a Claude Code plugin or publish to the Claude marketplace. Works on both claude.ai (generates files as code blocks) and Claude Code (writes and pushes files).

route-handlers

2707
from davepoon/buildwithclaude

This skill should be used when the user asks to "create an API route", "add an endpoint", "build a REST API", "handle POST requests", "create route handlers", "stream responses", or needs guidance on Next.js API development in the App Router.