AgendaViva can read, cache and announce changes, but nothing produces them. In 04-05 you had to write the district cookie from the console, and the spots only go down if you change them in the database. Writing in a SPA means designing an endpoint, calling it with fetch, managing states and then remembering to request the data again. Next.js offers another path: server functions that are called from a form or a component, and whose response already brings the updated screen.
In this lesson you'll see what they are, what travels over the network when they're invoked and how many ways there are to do it. You'll write two: one saves the district and the other books spots without two people being able to take the same one. Thorough validation, error messages and waiting states fill the next lessons; signing in, module 8. Until then we'll work with a placeholder user.
- What a Server Action is
A Server Function is an asynchronous function marked with 'use server'. Its code stays on the server; the browser only receives a reference, that is, an identifier it can use to ask for it to run. When it's used to modify data through React's mechanisms (<form action>, formAction or a transition), it's called a Server Action. In practice the two names are used almost interchangeably.
Route Handler with fetch |
Server Action | |
|---|---|---|
| Address | You choose it | The address of the page that invokes it, with a generated identifier |
| Method | Whichever you export | Always POST |
| Types between client and server | You assert them | The function's own |
| Updating the screen afterwards | Another request | In the same response |
| Works without JavaScript | Only with a form of your own | Yes, from <form action> |
| Called by another system | Yes | Not what it's for |
They don't replace Route Handlers: a mobile app, a webhook or the live spots from 04-06 still need a stable URL. And they're not for reading: the browser sends them one at a time and their result isn't cached.
- Declaring them
2.1. In a file
// actions/example.ts
'use server'
export async function archiveNotice(id: string): Promise<void> {
// …
}The directive on the first line turns everything the module exports into a Server Function. That's the form we'll use, in the actions/ folder planned in 01-03, because Client Components can import it too. Its rules:
- Only asynchronous functions can be exported. A constant or a synchronous function causes an error. Types are allowed, because they disappear at build time; shared values go in another module.
- Whatever isn't exported is private. A helper function without
exportcan't be invoked from outside. - Arguments and the result are serialized under the rules from 03-03: strings, numbers,
Date, plain objects,Map,FormData… No regular functions and no class instances. - The file doesn't carry
'use client', and doesn't need it. Norserver-only, although you can add it.
2.2. In a function
// Example only
async function ArchiveButton({ id }: { id: string }) {
async function archive() {
'use server'
await markAsArchived(id)
}
return (
<form action={archive}>
<button>Archive</button>
</form>
)
}Inside a Server Component, the directive can go in the function. It's convenient, and it has a consequence: id is a captured variable, so it travels to the browser and back. Next.js encrypts it along the way, but the documentation warns that you shouldn't rely on that encryption to protect a secret. In a separate file, by contrast, the inputs are in plain sight in the signature. For clarity, AgendaViva doesn't use actions inside components.
A Client Component can't declare any: it imports them or receives them as a prop.
- The first action: the preferred district
// actions/preferences.ts
'use server'
import { cookies } from 'next/headers'
import { listDistricts } from '@/lib/data/venues'
import { DISTRICT_COOKIE } from '@/lib/preferences'
const ONE_YEAR = 60 * 60 * 24 * 365
export async function saveDistrict(formData: FormData): Promise<void> {
const district = formData.get('district')
const cookieStore = await cookies()
if (typeof district !== 'string' || !(await listDistricts()).includes(district)) {
cookieStore.delete(DISTRICT_COOKIE)
return
}
cookieStore.set(DISTRICT_COOKIE, district, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: ONE_YEAR,
})
}- It receives
FormData. React passes it to any function placed in a form'saction, with one value for each field that has aname. formData.getreturnsstring | File | null. Nothing guarantees that the field exists or that it's text: anyone could have written the request.- It's validated against the real districts. Anything that doesn't fit, including the "None" option, deletes the preference. There's a second check when reading, in
getPreferredDistrict, and both are needed: between one and the other, the visitor could have edited the cookie. httpOnlyprevents reading it from JavaScript: nobody in the browser needs it.securerestricts it to HTTPS, except in development. These options are explained in 08-01.- Here you can write a cookie, unlike while rendering (04-05): the response hasn't started being sent yet.
// app/(public)/_components/district-form.tsx
import { saveDistrict } from '@/actions/preferences'
import { listDistricts } from '@/lib/data/venues'
import { getPreferredDistrict } from '@/lib/preferences'
export async function DistrictForm() {
const preferred = (await getPreferredDistrict()) ?? ''
const districts = await listDistricts()
return (
<form action={saveDistrict} className="mt-12 flex items-end gap-2">
<label className="flex flex-col">
Your district
<select key={preferred} name="district" defaultValue={preferred} className="border px-2">
<option value="">None</option>
{districts.map((district) => (
<option key={district}>{district}</option>
))}
</select>
</label>
<button className="border px-3">Save</button>
</form>
)
}// app/(public)/page.tsx, before YourDistrictEvents
<Suspense fallback={<div aria-hidden className="mt-12 h-12" />}>
<DistrictForm />
</Suspense>Try it: choose "Riverside" and save. Without reloading, the district's events appear. There's no 'use client', no fetch, no state and no call to refresh. A Server Component has put a server function in a form.
The key on the <select> isn't decorative. When a form action finishes successfully, React resets uncontrolled fields to their default value. And on a <select> that's already mounted, changing defaultValue has no effect. Without the key, the dropdown would go back to the value it was created with. With it, changing the preference creates a new one with the right value. This reset will come up again in 06-02.
Besides what's new, notice what hasn't been invalidated: no tags at all. The cookie isn't in any cache, and the district list is cached per district, not per person. Next.js renders the page again because the action has modified a cookie.
- What travels over the network
Open the network tab and save another district. There's a single request:
sequenceDiagram
participant B as Browser
participant S as Server
B->>S: POST / with the Next-Action header and the FormData
Note over S: 1. Runs saveDistrict
Note over S: 2. Renders the current route again
S-->>B: Set-Cookie + return value + RSC Payload of the page
Note over B: React updates what has changed
- The address is that of the page you're on. The action's identifier travels in the
Next-Actionheader; it's generated at build time and changes between builds. - One response brings two things: what the function returns and the current route rendered again. There's no second request to refresh.
- The new screen only travels if there's a reason. The reasons are the ones you know from 05-04, plus one more:
| The action… | Is the current route rendered again? |
|---|---|
Calls updateTag, revalidatePath or refresh |
Yes |
Calls revalidateTag with { expire: 0 } |
Yes |
| Writes or deletes a cookie | Yes |
Calls redirect |
The destination route is sent |
Calls revalidateTag with 'max' |
No |
| None of the above | No: only the return value travels |
- One at a time. If the visitor triggers three, the browser waits for each one before sending the next, so that the screen that arrives matches the latest result.
Promise.allwith several actions doesn't run them in parallel: if you need simultaneous work, do it inside one. The ordering is per browser; the server handles different people's actions at the same time. - If it throws an error, the promise is rejected on the client. In production the original message isn't sent: a generic one arrives with its
digest, just as in 02-04.
- Ways to invoke it
The form is the preferred one. A button can also carry its own action, which replaces the form's:
<form action={save}>
{/* fields */}
<button>Save</button>
<button formAction={discard}>Discard</button>
</form>When there's no form, it's called like a function, inside a transition:
// Example only
'use client'
import { useTransition } from 'react'
import { archiveNotice } from '@/actions/example'
export function ArchiveButton({ id }: { id: string }) {
const [isPending, startTransition] = useTransition()
return (
<button
disabled={isPending}
onClick={() => startTransition(async () => archiveNotice(id))}
>
Archive
</button>
)
}An onClick={() => archiveNotice(id)} would also run, but without isPending, without an optimistic update and without a failure reaching the error boundary: it would be a rejected promise nobody handles. The transition provides all three (06-04).
Finally, it can be invoked in an effect, for things that happen without anyone pressing anything, such as counting a visit:
useEffect(() => {
startTransition(async () => {
await countVisit(slug)
})
}, [slug, startTransition])This is the form that calls for the most care. In development, React runs effects twice. With Cache Components, on top of that, the page is hidden when you leave and its effects run again when you come back (02-01): you'd count two visits. An action triggered this way must tolerate repetitions. If what you want is to read data on mount, the answer is a Server Component; and if it's logging something after responding, after (07-04).
| From | When | Without JavaScript |
|---|---|---|
<form action> |
Almost always | Works |
formAction |
Several operations on the same fields | Works |
| Event, with a transition | Dragging, toggling, keyboard shortcuts | No |
| Effect, with a transition | Things that happen without a user gesture | No |
- Passing arguments
The booking form needs the event's identifier, which nobody types. There are three ways:
// 1. bind: a fixed argument, placed before FormData
<form action={bookSpots.bind(null, event.id)}>
// 2. Hidden field: one more piece of FormData
<input type="hidden" name="eventId" value={event.id} />
// 3. A captured variable in an action written inside the component (section 2.2)bind(null, event.id) produces another function whose first argument is already set: the action will be bookSpots(eventId, formData). It works in both kinds of component and without JavaScript. We prefer it to the hidden field because the argument arrives with its type and isn't mixed in with the fields.
None of the three protects the value. The identifier fixed with bind goes out to the browser and comes back from it, and anyone who wants to can send a different one. bind is a convenience, not security.
- Progressive enhancement
Disable JavaScript in the browser's tools, reload the home page and change the district. It works: React includes in the form's HTML the hidden fields that identify the action, the browser makes a regular POST, and the server runs it and responds with the whole document.
It matters more than it seems. Not because of people browsing without JavaScript, who are few, but because of everyone during the first few seconds: with poor coverage, the HTML arrives before the code. With a form in a Server Component, pressing before hydration still submits. In one rendered by a Client Component, React queues the submission and prioritizes hydrating it.
It's preserved as long as action receives a Server Action, with or without bind. It's lost if it receives a client function that wraps it, or if you use onSubmit or onClick.
- Booking spots
8.1. The placeholder user
// lib/placeholder-user.ts
import 'server-only'
import { PLACEHOLDER_ORGANIZER_ID } from '@/lib/data/dashboard'
import type { User } from '@/lib/types'
// TEMPORARY: fixed identities until there are sessions (module 8).
// While this module is in use, the application must NOT be deployed.
type PlaceholderUser = Pick<User, 'id' | 'role'>
export async function getPlaceholderUser(): Promise<PlaceholderUser> {
return { id: 'usr-01', role: 'visitor' }
}
export async function getPlaceholderOrganizer(): Promise<PlaceholderUser> {
return { id: PLACEHOLDER_ORGANIZER_ID, role: 'organizer' }
}Everyone who books will be usr-01, so there's no authentication or authorization. The functions are asynchronous, as reading the session will be, so that in module 8 the change comes down to replacing the call. The important part is already decided: the server works out the identity. No action will accept a userId as an argument, because then everyone would choose who they are.
8.2. The last-spot problem
The code you'd write at first reads the spots, checks and writes. With two people at the same time:
sequenceDiagram
participant A as Booking A
participant B as Booking B
participant D as Database
A->>D: how many are left?
D-->>A: 1
B->>D: how many are left?
D-->>B: 1
A->>D: spots = 0 and insert booking
B->>D: spots = 0 and insert booking
Note over D: two bookings for one spot
A transaction doesn't prevent it on its own: with PostgreSQL's default isolation level, both can read the same 1. You have to stop the second from reading until the first finishes, and for that you lock the row with SELECT … FOR UPDATE:
// lib/data/bookings.ts
import 'server-only'
import { and, eq, sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { bookings, events } from '@/lib/db/schema'
import type { Booking } from '@/lib/types'
export type BookingResult =
| { status: 'booked'; spotsBefore: number; spotsAfter: number }
| { status: 'already-booked' }
| { status: 'not-enough-spots'; spotsLeft: number }
| { status: 'unavailable' }
export async function getBooking(
userId: string,
eventId: string,
): Promise<Pick<Booking, 'id' | 'spots'> | null> {
const db = await getDb()
const [booking] = await db
.select({ id: bookings.id, spots: bookings.spots })
.from(bookings)
.where(and(eq(bookings.userId, userId), eq(bookings.eventId, eventId)))
.limit(1)
return booking ?? null
}
export async function createBooking(
userId: string,
eventId: string,
spots: number,
): Promise<BookingResult> {
const db = await getDb()
return db.transaction(async (tx): Promise<BookingResult> => {
// 1. Lock the event: another booking for the same one waits here
const [event] = await tx
.select({ status: events.status, endsAt: events.endsAt, spotsLeft: events.spotsLeft })
.from(events)
.where(eq(events.id, eventId))
.for('update')
if (!event || event.status !== 'published' || event.endsAt <= new Date()) {
return { status: 'unavailable' }
}
// 2. One booking per person and event
const [existing] = await tx
.select({ id: bookings.id })
.from(bookings)
.where(and(eq(bookings.userId, userId), eq(bookings.eventId, eventId)))
if (existing) return { status: 'already-booked' }
// 3. Do they fit?
if (event.spotsLeft < spots) return { status: 'not-enough-spots', spotsLeft: event.spotsLeft }
// 4. Write both things
await tx.insert(bookings).values({ userId, eventId, spots })
await tx
.update(events)
.set({ spotsLeft: sql`${events.spotsLeft} - ${spots}` })
.where(eq(events.id, eventId))
return {
status: 'booked',
spotsBefore: event.spotsLeft,
spotsAfter: event.spotsLeft - spots,
}
})
}.for('update')holds the event's row until the transaction ends. Booking B waits at step 1, and when it continues it reads what A left. Only bookings for the same event block each other; reading isn't blocked, so event pages don't notice.- Inside, you use
tx, neverdb. A query made withdbwould go through another connection, outside the transaction. - The transaction is short. Queries only. An API call or sending an email inside it would keep the row locked and the connection busy.
- Expected rejections are values. Leaving with
returncommits a transaction that hasn't written anything. An exception rolls it all back. - The 2, 3 order makes sense. Someone who double-clicked on the last spots should read "you already have a booking", not "there are no spots left".
- The constraints from 04-02 are still the last line of defense. If some other code forgot the lock,
bookings_event_userandevents_valid_spotswould make the write fail. They aren't the usual mechanism, because an error explains nothing to the person booking, but they keep the data from ending up wrong.
There's another technique without an explicit lock: an UPDATE … WHERE spots_left >= n, then checking whether it affected any row. It's just as safe; it would lose the detail of why it was rejected.
8.3. The action
// actions/bookings.ts
'use server'
import { refresh } from 'next/cache'
import { createBooking } from '@/lib/data/bookings'
import { readEnv } from '@/lib/env'
import { notifyIfAvailabilityChanges } from '@/lib/revalidation'
import { getPlaceholderUser } from '@/lib/placeholder-user'
export async function bookSpots(eventId: string, formData: FormData): Promise<void> {
const user = await getPlaceholderUser()
const spots = Number(formData.get('spots'))
const { maxSpotsPerBooking } = readEnv()
if (!Number.isInteger(spots) || spots < 1 || spots > maxSpotsPerBooking) {
throw new Error('Invalid number of spots')
}
const result = await createBooking(user.id, eventId, spots)
if (result.status === 'booked') {
notifyIfAvailabilityChanges(result.spotsBefore, result.spotsAfter)
}
refresh()
}It's a thin function: identity, input, operation and notifications. The business rule lives in lib/data/bookings.ts, which can be tested and reused without going through a form.
The notifications are the ones decided in 05-04 and they're sent after db.transaction has finished. refresh is always called, after a rejection too: if the spots ran out, the screen has to show it.
8.4. The block on the event page
// app/(public)/events/_components/event-booking.tsx
import { bookSpots } from '@/actions/bookings'
import { getAvailability } from '@/lib/data/events'
import { getBooking } from '@/lib/data/bookings'
import { readEnv } from '@/lib/env'
import { getPlaceholderUser } from '@/lib/placeholder-user'
import type { AgendaEvent } from '@/lib/types'
export async function EventBooking({ event }: { event: AgendaEvent }) {
const user = await getPlaceholderUser()
const [booking, availability] = await Promise.all([
getBooking(user.id, event.id),
getAvailability(event.slug),
])
if (booking) return <p className="mt-4">You have {booking.spots} spots booked.</p>
if (!availability || event.endsAt <= new Date()) return null
const { maxSpotsPerBooking } = readEnv()
const max = Math.min(maxSpotsPerBooking, availability.spotsLeft)
if (max === 0) return null // LiveAvailability already says "Fully booked"
return (
<form action={bookSpots.bind(null, event.id)} className="mt-4 flex items-end gap-2">
<label className="flex flex-col">
Spots
<input
type="number"
name="spots"
min={1}
max={max}
defaultValue={1}
required
className="border px-2"
/>
</label>
<button className="border px-3">Book</button>
</form>
)
}// EventDetails, after the spots block
<ErrorBoundary title="We can't show the booking">
<Suspense fallback={<p className="mt-4 h-12">Checking your booking…</p>}>
<EventBooking event={event} />
</Suspense>
</ErrorBoundary>The component isn't cached: it depends on who's looking. When prerendering, it stops at getDb, inside its <Suspense>, and both the clock and the environment are read afterwards, during the request. That fulfills the promise made in 03-05 about MAX_SPOTS_PER_BOOKING.
Book on pottery-workshop: the form gives way to the message. On riverside-quartet you'll see the message straight away, because usr-01 has a booking in the seed data. Notice, though, that the "… of … spots left" figure can take a few seconds to go down: SWR holds that number in the browser, and refresh doesn't reach it. That's solved in 06-04.
You can also see the lock. Seed again, open an event page without a booking and, in a terminal, hold the row:
docker compose exec db psql -U agendaviva
# agendaviva=# begin;
# agendaviva=# select title from events where slug = 'pottery-workshop' for update;
# Now press "Book" in the browser: it keeps waiting
# agendaviva=# commit;
# The booking continues at that very moment
- They're public endpoints
The convenience of calling a function makes you forget what's underneath: a POST that anyone can send, with whatever arguments they like and without going through your form. Only rendering the button for people who can use it protects nothing. Neither does TypeScript: eventId: string describes what your code sends.
Next.js puts up some barriers: identifiers that can't be guessed and that change between builds, removal of actions nobody uses, comparing the Origin with the domain to stop requests from other sites, and a 1 MB limit on the body. None of them replaces these checks, which belong in every action:
| Check | In AgendaViva |
|---|---|
| Who is it? | Pending: placeholder user until 08-02 |
| Can they do this to this piece of data? | Largely pending: 08-04 |
| Does the input have the right shape? | Minimal for now; with Zod in 06-03 |
| Does it return only what's needed? | Yes: never full rows |
| Can it be abused by repetition? | Pending: 08-06 |
Action security has its own lesson, 08-06. Until then, the application only lives on your machine.
Common Mistakes and Tips
- Exporting constants from a
'use server'file. Only asynchronous functions and types. - Using actions to read. They run in series and aren't cached.
- Accepting the user as an argument. Identity comes from the server.
- Believing that
bindor a hidden field protects a value. - Reading, checking and writing without a lock, or querying with
dbinside the transaction. - Making external calls inside a transaction.
- Not calling anything that renews the screen: the write happens and nobody sees it.
- Invoking from
onClickwithout a transition. No pending state, and errors nobody handles. - Throwing errors for expected rejections. In production the message doesn't arrive; return values instead (06-02).
- Counting in an effect without tolerating repetitions.
Exercises
Exercise 1: deleting the preference
Add a "Forget" button to the district form that deletes the cookie with an action of its own, visible only if there's a preference. Explain why it doesn't need refresh and why the form keeps working without JavaScript.
Solution
// actions/preferences.ts (addition)
export async function forgetDistrict(): Promise<void> {
const cookieStore = await cookies()
cookieStore.delete(DISTRICT_COOKIE)
}Deleting a cookie in an action already causes the current route to be rendered. And formAction receives a Server Action, so React can write into the HTML whatever a regular submission needs. The function doesn't take formData because it doesn't use it; React passes it anyway and it's ignored. It's just practice: the "None" option does the same.
Exercise 2: reviewing an action
Find the problems in this action, assuming it's invoked with cancel.bind(null, user.id, booking.id).
'use server'
export const INITIAL_STATE = { error: null }
export async function cancel(userId: string, bookingId: string) {
const db = await getDb()
const [booking] = await db.delete(bookings).where(eq(bookings.id, bookingId)).returning()
await db
.update(events)
.set({ spotsLeft: sql`${events.spotsLeft} + ${booking.spots}` })
.where(eq(events.id, booking.eventId))
return booking
}Solution
- It exports a constant: an error in a
'use server'file. - It receives
userIdfrom the browser and, on top of that, doesn't use it: anyone can delete any booking with its identifier. It must be obtained on the server and appear in the delete'swhere. - The two writes aren't in a transaction: if the second one fails, spots are lost.
- If the booking doesn't exist,
bookingisundefinedand readingspotsthrows an error. With a double click it will happen. - It returns the full row to the browser.
- It doesn't call
refreshornotifyIfAvailabilityChanges: neither the screen nor the listings find out. - It queries the database directly; the operation should be in
lib/data/bookings.ts. You'll write the correct version in 06-04.
Exercise 3: choosing the mechanism
Say whether you'd use a Server Action, a Route Handler or a Server Component: (a) a contact form; (b) exporting an event's bookings as a CSV file; (c) showing the booking history; (d) receiving a notification from an external provider; (e) marking an event as featured from the dashboard; (f) checking, while someone types, whether a title already exists.
Solution
- (a) A Server Action in a
<form>: your own write, with progressive enhancement. - (b) A Route Handler with
GET: it's a download with its own URL and headers. - (c) A Server Component: it's a read.
- (d) A Route Handler with
POST: the caller is another system (07-03). - (e) A Server Action.
- (f) A Route Handler with
GETand SWR, like the suggestions in 04-06. Actions run in series and would pile up while typing.
Conclusion
A Server Action is an asynchronous function marked with 'use server' that the browser calls with a POST. From a form it receives FormData, it works without JavaScript, and it responds with the result and the screen rendered again, if a cookie was written or a render was requested with refresh, updateTag or revalidatePath. Arguments are fixed with bind and can never be trusted. The logic lives in the data layer: booking locks the event's row inside a transaction and returns a value for each outcome.
Those outcomes, however, get lost. If there are no spots left, the person booking reads no reason at all, and an invalid number takes them to an error screen. In Forms with useActionState the action will return a state the form knows how to show, and you'll write AgendaViva's biggest form: creating and editing events in the dashboard.
