Menu

What Are Server Actions?

Lesson 1: What Are Server Actions?

What is a Server Action?

A Server Action is an async function that runs on the server and can be called from the client. You mark it with the 'use server' directive.

Approach Steps to save a form
API route + client fetch Create route.ts → write fetch with JSON → manage loading and errors → refresh data
Server Action Write one function → pass it to <form action={...}>

Example

// app/courses/[slug]/actions.ts
'use server';

import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';

export async function addReview(formData: FormData) {
  const courseId = formData.get('courseId') as string;
  const text = formData.get('text') as string;
  const rating = Number(formData.get('rating'));

  await db.review.create({ data: { courseId, text, rating } });
  revalidatePath(`/courses/${courseId}`);
}
// app/courses/[slug]/ReviewForm.tsx (can be a Server Component)
import { addReview } from './actions';

export function ReviewForm({ courseId }: { courseId: string }) {
  return (
    <form action={addReview}>
      <input type="hidden" name="courseId" value={courseId} />
      <select name="rating" defaultValue="5">
        {[5, 4, 3, 2, 1].map((n) => <option key={n} value={n}>{n} stars</option>)}
      </select>
      <textarea name="text" required />
      <button type="submit">Post review</button>
    </form>
  );
}

How it works

  1. Next.js turns addReview into a server endpoint with a secret ID.
  2. Submitting the form sends a POST request with the form data.
  3. The action runs on the server, writes to the database, and revalidates the page.
  4. The updated page is returned in the same response, so the new review appears.
  5. The form works even before JavaScript has loaded (progressive enhancement).
Where to define How
Separate file (recommended) 'use server' at the top; every export is an action
Inside a Server Component 'use server' as the first line of the function body
Called from a Client Component Import from a 'use server' file

Passing extra arguments: use bind instead of hidden inputs:

const addReviewForCourse = addReview.bind(null, course.id);
// action signature: addReview(courseId: string, formData: FormData)

Common mistakes

Mistake Effect Fix
Treating actions as private functions Anyone can call them with a crafted request Check authentication and permissions inside every action (Module 9)
Using actions for reading data Requests run one at a time; no caching Fetch in Server Components
Returning large or non-serialisable values Errors or slow responses Return small plain objects

Key takeaways

  • Server Actions are server functions called from forms and buttons.
  • They work without JavaScript and update the page in one round trip.
  • They are public endpoints: always validate and authorise.

Try it: Create an addReview action and a review form on the course page that saves reviews to your database or a JSON file.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details