Script Valley
Next.js: Full-Stack React Applications
API Routes and Server ActionsLesson 3.2

What are Server Actions and how do they replace API routes for mutations

Server Actions, use server directive, form actions, server-side mutations, revalidatePath, revalidateTag, action prop on form

Server Actions: Server Functions Called from Client

Server Actions are async functions marked with 'use server'. They run on the server but can be called directly from Client Components or HTML forms โ€” no API route, no fetch call required.

// app/actions/posts.ts
'use server'
import { revalidatePath } from 'next/cache'

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string
  const content = formData.get('content') as string

  await db.post.create({ data: { title, content } })
  revalidatePath('/blog')  // Refresh the blog page cache
}

Using an Action in a Form

// app/blog/new/page.tsx
import { createPost } from '@/app/actions/posts'

export default function NewPostPage() {
  return (
    <form action={createPost}>
      <input name="title" type="text" required />
      <textarea name="content" required />
      <button type="submit">Publish</button>
    </form>
  )
}

revalidatePath and revalidateTag

After a mutation, call revalidatePath('/blog') to bust the cache for that route. Use revalidateTag('posts') if you tagged your fetch calls with { next: { tags: ['posts'] } }. Tag-based revalidation is more precise โ€” it invalidates only the specific data across all pages that use it, not the entire route.

Up next

How to handle form state and errors with useActionState in Next.js

Sign in to track progress

What are Server Actions and how do they replace API routes for mutations โ€” API Routes and Server Actions โ€” Next.js: Full-Stack React Applications โ€” Script Valley โ€” Script Valley