Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NX
Next.js
0/10 completed
Beginner
Why Next.js?Pages, layouts and routingLinks, images and fonts
Intermediate
Server and Client ComponentsFetching data and streamingRoute Handlers (API routes)Forms and Server Actions
Advanced
Caching and revalidationMetadata, SEO, errors and Proxy
Pro
Auth, deployment and production
Tracks / Next.js / Intermediate

Forms and Server Actions

Server Actions are async functions that run on the server but can be called directly from your components: from a <form action>, a button, or an event handler. There's no API route to write, no fetch call, and you get end-to-end type safety.

Your first Server Action

Mark a function with 'use server'. Put shared actions in their own file:

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

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

export async function createTodo(formData: FormData) {
  const text = String(formData.get('text') ?? '').trim();
  if (!text) return;

  await db.todo.create({ data: { text } });
  revalidatePath('/todos');            // refresh the page's data
}

Use it in a form, inside a Server Component:

tsx
// app/todos/page.tsx
import { createTodo } from '../actions';
import { db } from '@/lib/db';

export default async function TodosPage() {
  const todos = await db.todo.findMany();
  return (
    <>
      <form action={createTodo}>
        <input name="text" placeholder="New todo" required />
        <button type="submit">Add</button>
      </form>
      <ul>{todos.map((t) => <li key={t.id}>{t.text}</li>)}</ul>
    </>
  );
}

When the form is submitted, Next.js sends the FormData to the server, runs createTodo, and returns the updated UI in a single round trip.

Progressive enhancement: forms in Server Components work even before JavaScript loads, or with JavaScript disabled. They submit like classic HTML forms.

⚠️ Security: every action is a public endpoint

Behind the scenes, a Server Action is reachable with a direct POST request, not only through your UI. Always authenticate and authorise inside the action, and validate the input:

ts
'use server';

import { z } from 'zod';
import { auth } from '@/lib/auth';
import { updateTag } from 'next/cache';

const Schema = z.object({ title: z.string().min(1).max(200), body: z.string().max(10_000) });

export async function createPost(formData: FormData) {
  const session = await auth();
  if (!session?.user) throw new Error('Unauthorized');                  // 1. who is calling?

  const parsed = Schema.safeParse(Object.fromEntries(formData));        // 2. is the input valid?
  if (!parsed.success) return { ok: false, errors: parsed.error.flatten().fieldErrors };

  await db.post.create({ data: { ...parsed.data, authorId: session.user.id } });   // 3. act
  updateTag('posts');                                                    // 4. refresh cached data
  return { ok: true };
}

Pending states and results: useActionState

In a Client Component, useActionState gives you the action's return value and a pending flag:

tsx
// app/subscribe-form.tsx
'use client';

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

export function SubscribeForm() {
  const [state, formAction, pending] = useActionState(subscribe, { message: '' });
  return (
    <form action={formAction}>
      <input name="email" type="email" required />
      <button disabled={pending}>{pending ? 'Subscribing…' : 'Subscribe'}</button>
      {state.message && <p aria-live="polite">{state.message}</p>}
    </form>
  );
}
ts
// app/actions.ts
'use server';
export async function subscribe(prevState: { message: string }, formData: FormData) {
  const email = String(formData.get('email'));
  await saveSubscriber(email);
  return { message: `Thanks! ${email} is subscribed.` };
}

Here's the client-side half, running live. The "server action" is simulated with a delay:

Optimistic updates: useOptimistic

Show the result immediately, before the server confirms it:

After a mutation: refresh, redirect

Function (from next/cache / next/navigation) Effect
revalidatePath('/posts') Re-render that path with fresh data
updateTag('posts') Immediately expire cached data tagged 'posts' (read-your-own-writes)
revalidateTag('posts', 'max') Mark tagged data stale; serve the old data while fresh data loads in the background
refresh() Refresh the client router so the UI shows the latest state
redirect('/posts/123') Send the user to another page
ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';

export async function createPost(formData: FormData) {
  const post = await db.post.create({ data: { title: String(formData.get('title')) } });
  revalidatePath('/posts');
  redirect(`/posts/${post.id}`);     // redirect throws internally, so call it last
}

Passing extra arguments with bind

tsx
// Server Component
import { deletePost } from './actions';

export function DeleteButton({ id }: { id: string }) {
  const deleteWithId = deletePost.bind(null, id);    // deletePost(id, formData)
  return (
    <form action={deleteWithId}>
      <button>Delete</button>
    </form>
  );
}

Practice (in your project)

Build a guestbook:

  1. A Server Component page lists messages from an in-memory array (or a database).
  2. A form posts name and message to a Server Action that validates them (name 1–50 characters, message 1–280).
  3. Use a Client Component with useActionState to show validation errors and a pending button.
  4. Call revalidatePath so the new message appears.
✎ Check your understanding

1.What is the most important security rule for Server Actions?

2.Which hook gives you a pending flag and the action's returned state?

← Route Handlers (API routes)
React · live preview
Preview
React · live preview
Preview