Sub topic 13
Bundler and Framework Support, and Refreshing Data After a Mutation
The earlier chapters covered how to write Server Functions and how to secure them. This chapter covers two practical questions. What has to be set up for "use server" to work at all? And once a Server Function changes data, how does the page show the new data?
It assumes you can write Server Functions and call them from forms and transitions. It also assumes you know what a Server Component is and understand the security model from the previous chapter.
Why `"use server"` needs build tooling
"use server" is only a marker. React does not read it at runtime and send your function somewhere. A bundler (the tool that combines your source files into the files the browser and server run) has to recognize the directive and rewrite your code.
When a Client Component imports a function from a "use server" file, the bundler does not put the function body in the browser bundle. It replaces the import with a reference, which is a small stub holding an identifier for the function. Calling the stub sends a network request that carries the identifier and the serialized arguments. The server looks up the identifier, runs the real function, and sends back the result.
This has three consequences:
- Plain React with a basic bundler setup cannot run Server Functions. You need a bundler or framework that implements the React Server Components protocol.
- Your server code never reaches the client bundle, but its identifier and endpoint do. This is why the previous chapter treated every Server Function as a public endpoint.
- The server and the client must be built together, so they agree on the identifiers.
What the framework supplies
React defines the directive and the calling convention. A framework supplies everything around them. Without these pieces, a Server Function would run, but you would have no good way to use it.
| Concern | Provided by | Example |
|---|---|---|
| Compiling `"use server"` into references | Bundler plugin or framework | Next.js build, RSC-enabled Vite or Parcel setups |
| The HTTP endpoint that receives calls | Framework | A POST request to a route the framework manages |
| Routing and rendering Server Components | Framework | App Router pages and layouts |
| Caching of fetched data | Framework | Next.js data and route caches |
| Invalidating that cache after a write | Framework | `revalidatePath` from `next/cache` |
| Redirecting after a write | Framework | `redirect` from `next/navigation` |
The last three rows are why this chapter exists. React has no built-in concept of "the data on this page is now stale." The framework owns caching and routing, so the framework gives you the tools for refreshing. The examples below use Next.js. Other frameworks use different function names for the same ideas.
Refreshing data after a mutation
The stale page problem
Suppose a page lists notes and has a form that adds one. The form calls a Server Function that inserts a row. The insert succeeds, but the list on screen still shows the old notes. The Server Component that rendered the list ran before the mutation, and nothing told it to run again.
You have to tell the framework which data is out of date. After that, the framework re-renders the affected Server Components with fresh data and sends the new UI to the browser.
Revalidating a path
In Next.js, revalidatePath marks the cached data for a route as stale. Call it at the end of the Server Function, after the write succeeds.
// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
await db.notes.insert({ title });
revalidatePath('/notes');
return { error: null };
}The page that shows the notes is an ordinary Server Component:
// app/notes/page.js (a Server Component)
import { db } from '../db';
import { NoteForm } from '../NoteForm';
export default async function NotesPage() {
const notes = await db.notes.list();
return (
<main>
<h1>Notes</h1>
<NoteForm />
<ul>
{notes.map((note) => (
<li key={note.id}>{note.title}</li>
))}
</ul>
</main>
);
}NoteForm is the useActionState component from the earlier chapter. When the user submits, three things happen in one round trip:
- The Server Function writes the note and calls
revalidatePath('/notes'). - The framework re-renders the
/notesroute on the server with fresh data. - The response carries both the function's return value (the new
state) and the updated UI, so the list and the form state update together.
The one-round-trip behavior is a framework feature. In Next.js, calling revalidatePath or a similar function inside a Server Function lets the framework return the refreshed UI in the same response as the action result. You do not have to write a second fetch.
Choosing what to revalidate
Revalidating a whole path is the simplest option. It can be more than you need. Frameworks usually offer finer tools too. Next.js lets you tag cached data and invalidate by tag. The tag functions have changed signature between versions, so read the documentation for your version. The decision rule is the same everywhere:
- Invalidate the narrowest scope that covers every place showing the changed data.
- If a layout shows a count of notes, revalidating only the list page leaves the layout stale.
- If you are unsure, revalidate more. A needless re-render costs time. A missed one shows wrong data.
Redirecting after a write
Sometimes the right response to a mutation is to send the user elsewhere, such as to the new note's page. Use the framework's redirect function.
// app/actions.js
'use server';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { db } from './db';
export async function createNoteAndOpen(formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
throw new Error('Title is required.');
}
const note = await db.notes.insert({ title });
revalidatePath('/notes');
redirect(`/notes/${note.id}`);
}Two details matter here. First, redirect works by throwing a special error that the framework catches. If you wrap it in try/catch, your catch block receives that error and the redirect never happens. Call redirect outside any try block, or rethrow errors you do not recognize. Second, call revalidatePath before redirect, because code after redirect does not run.
Client state is separate
Revalidation refreshes server-rendered output. It does not reset Client Component state by itself. In the notes example, the title the user typed stays in the input unless something clears it. For uncontrolled inputs inside a <form action={...}>, React resets the form after a successful action, but state you hold in useState is yours to manage. If a Client Component displays a list it received as props, the new props arrive after the refresh. If it copied those props into its own state, the copy will not update.
Failure modes and gotchas
- Missing revalidation. The most common bug. The write succeeds and the UI looks unchanged until a manual reload. Add the revalidation call to the function, not to the component that calls it, so every caller gets it.
- Revalidating before the write finishes. Always
awaitthe database write first. Otherwise the re-render can read the old data. - Mutations that don't go through the framework. If another service or a cron job changes the data, your Server Function's revalidation never runs. Use time-based or tag-based invalidation for those cases.
- Sequential calls. Some frameworks queue Server Function calls from the client and run them one at a time. Do not count on them running in parallel for speed, and do not count on a specific order across separate user actions.
- Dead code and identifiers. Build tools may drop Server Functions that are never imported and may generate new identifiers on each build. A browser tab left open across a deployment can call an identifier that no longer exists. Treat that as an expected failure and handle it, for example by asking the user to reload.
- Hosting. Server Functions need a server runtime, so a purely static export cannot run them. Confirm that your hosting target supports your framework's server features.
Summary checklist
- Use a bundler or framework that explicitly supports React Server Components and Server Functions.
- After each successful write, invalidate the cache for every route or tag that shows the changed data.
- Call
redirectlast and outsidetry/catch. - Keep security checks in the function, as the previous chapter described. Revalidation does nothing for security.
Exercise
A Server Function inserts a note and then the page still shows the old list until the user reloads. The function body is: await db.notes.insert({ title }); return { error: null };. What is missing, and where should you add it?
Show answer
The function never tells the framework that the cached data is stale. Add a revalidation call, such as revalidatePath('/notes') in Next.js, inside the Server Function after the await db.notes.insert(...) line and before the return. Putting it in the function means every caller gets the refresh, and the framework can return the updated UI in the same response.
Exercise
This function never navigates, even though the insert works:
try {
const note = await db.notes.insert({ title });
redirect(/notes/${note.id});
} catch (e) {
return { error: 'Could not save.' };
}
Why does the redirect fail, and how do you fix it?
Show answer
redirect throws a special error that the framework uses to perform the navigation. The catch block catches it and returns an error object instead, so the framework never sees the signal. Move redirect outside the try block (for example, store note in a variable declared before the try, and call redirect after the try/catch), or rethrow errors you do not recognize.
Exercise
Why can't a project with a basic bundler setup and no Server Components support run a "use server" function, even though the file is valid JavaScript?
Show answer
The directive is only a marker. A supporting bundler or framework must rewrite imports of "use server" functions into references with identifiers, keep the function bodies out of the client bundle, and provide the server endpoint that receives calls and runs the functions. Without that tooling, nothing replaces the import or handles the request.