Sub topic 14
Security: what the payload exposes
This chapter assumes you have read the earlier chapters on the RSC payload, client references, serialization rules and Server Functions. You should be comfortable with "use client" and "use server". The goal here is to treat the server-to-client boundary as a trust boundary. You will learn what leaves the server, what comes back in, and which mistakes cause leaks.
The payload is data sent to the browser
The RSC payload is a stream the browser receives and can read. Anyone with developer tools can open the network tab and read every row. Server Components run on the server, but their output does not stay there.
Three things reach the browser:
- Rendered output. Elements, text and attributes from Server Components, as in the
main,h1andlirows of the sample payload. - Props passed to Client Components. A prop on a
$L1row is serialized into the payload as plain data, like{"initial":1}in the earlier example. - Client references. Module paths and chunk names, such as
app/Counter.jsandchunk-counter.js. These reveal your file structure and bundle layout, but not any server-only source code.
Server Component source code, server-only imports, environment variables, and database clients are not sent. The server only sends what the component returns.
| Item | Reaches the browser? | Why |
|---|---|---|
| Server Component function body | No | It runs on the server and only its output is serialized. |
| Variables read inside a Server Component | Only if rendered or passed as props | Values must be placed in the tree to be sent. |
| Props given to a Client Component | Yes | The payload serializes them so the client can render. |
| Client Component source | Yes | It ships as a normal JavaScript chunk. |
| Client reference module names | Yes | The client needs them to load the chunk. |
The common leak: passing too much through props
The most frequent mistake is passing a whole database record to a Client Component because it is convenient. Everything on the object is serializable, so everything is sent.
// app/profile/page.js (Server Component)
import { getUser } from '../db';
import ProfileCard from './ProfileCard';
export default async function Page() {
const user = await getUser();
// user may include passwordHash, email, internalNotes, and more
return <ProfileCard user={user} />;
}If ProfileCard only displays user.name, the payload still contains passwordHash and internalNotes. The Client Component never uses them, but the browser receives them anyway.
The fix is to pick fields on the server and pass only those:
// app/profile/page.js (Server Component)
import { getUser } from '../db';
import ProfileCard from './ProfileCard';
export default async function Page() {
const user = await getUser();
const publicUser = { name: user.name, avatarUrl: user.avatarUrl };
return <ProfileCard user={publicUser} />;
}A better design is a data access function that returns a narrow shape. Then no caller can accidentally hand a full record to the client.
Server-only code and accidental imports
The reverse mistake is also possible. A Client Component imports a module that contains secrets or database code. The bundler then includes that module in a client chunk. Unlike the payload leak, this one exposes source code and any values inlined at build time.
The server-only package turns this into a build error. Importing it into a module marks that module as unusable from client code.
// app/data.js
import 'server-only';
export async function getUser(id) {
const res = await fetch(`https://internal.example.com/users/${id}`, {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
return res.json();
}If any Client Component imports app/data.js, directly or through other modules, the build fails. This is a cheap safeguard. Put it at the top of every module that touches secrets or databases.
Environment variables also need care. Frameworks usually expose only variables with a special prefix to client code. Check your framework's rule. Do not give a secret that prefix.
Taint APIs as a second line of defense
React provides experimental taint APIs that mark a value as not allowed to be serialized to the client. If the value reaches a Client Component prop, React throws instead of sending it.
// app/secrets.js
import 'server-only';
import { experimental_taintUniqueValue } from 'react';
experimental_taintUniqueValue(
'Do not pass the API key to the client.',
process,
process.env.API_KEY
);experimental_taintObjectReference does the same for one object instance, such as a user record. Both APIs are experimental, and their names and availability depend on your React version and framework. They catch some accidents but do not replace careful prop selection. A value that is copied, sliced, or transformed is no longer the tainted value.
Server Functions are public endpoints
A function in a "use server" module is a Server Function. The client calls it by reference, but the call is an HTTP request. The reference is not a secret, and a request does not have to come from your UI. An attacker can send a crafted request with any arguments.
This has three consequences:
- Validate all inputs. Arguments arrive from the network. Check types, ranges and lengths, as the earlier
addPostexample did. - Authenticate inside the function. Do not assume only logged-in users see the button that calls it. Hiding a button is not access control.
- Authorize the specific action. Confirm that the current user may act on the specific resource, not just that they are logged in.
// app/actions.js
'use server';
import { getSession } from './session';
import { db } from './db';
export async function deletePost(formData) {
const session = await getSession();
if (!session) {
throw new Error('Unauthorized');
}
const id = Number(formData.get('id'));
if (!Number.isInteger(id)) {
throw new Error('Invalid id');
}
const post = await db.posts.find(id);
if (!post || post.authorId !== session.userId) {
throw new Error('Forbidden');
}
await db.posts.delete(id);
}The getSession and db modules stand in for your own authentication and data layers. The structure is what matters. The function checks identity, validates the input, and then checks ownership, all on the server.
Some frameworks add protections, such as encrypting values captured by inline Server Functions, using non-guessable function identifiers, or removing unused functions from the build. These details vary and change between versions. Use them as extra layers, and never rely on them in place of checks inside the function.
Server Functions that change state also face cross-site request forgery (CSRF), where another site causes a logged-in user's browser to send a request. Frameworks often check the Origin header for these requests. Confirm that yours does, and keep session cookies set with SameSite.
Keep the request-handling stack patched
The server accepts serialized data from the client: Server Function arguments, and framework requests that encode a payload-like format. Parsing that data is itself a risk. React and the major frameworks have shipped security fixes for how the server handles these requests. Keep your react, react-server-dom-* packages and framework version current, and read advisories for them.
Where the trust boundary sits
Data flowing to the right is public. Data flowing back is untrusted.
Checklist for reviewing a component tree
- Find every
"use client"file and list its props. - For each prop, ask whether the whole value is safe to show to the user.
- Replace full records with narrow objects built on the server.
- Add
server-onlyto modules that use secrets, databases or private APIs. - Open each
"use server"file. Confirm each exported function validates input and checks authorization. - Open the network tab, find the payload, and search it for field names you did not mean to send.
Common errors
- Assuming server rendering hides data. Anything rendered or passed as a prop is in the payload.
- Checking permissions only in the UI. Server Functions must check them again.
- Trusting hidden form fields. Fields like
authorIdin aFormDatacan be edited. Derive identity from the session. - Exporting helpers from a
"use server"file. An exported helper becomes callable from outside. - Relying on taint APIs alone. They are experimental and match only specific values or objects.
Exercise
A Server Component fetches an order record that includes customerEmail and internalMargin. It renders <OrderSummary order={order} />, where OrderSummary is a Client Component that shows only order.id and order.total. Is internalMargin exposed, and what should you change?
Show answer
Yes. The whole object is serialized into the RSC payload as props, so internalMargin and customerEmail are visible in the network tab even though the component never renders them. Build a narrow object on the server, such as { id: order.id, total: order.total }, and pass that instead.
Exercise
A Server Function updateRole(formData) reads userId and role from the form and updates the database. The "Admin" page that shows the form is only reachable by admins. Why is this still unsafe, and what checks belong inside the function?
Show answer
The function is a public endpoint, so a request can reach it without going through the admin page. Inside the function, authenticate the caller with the session, verify the caller is an admin, and validate that userId and role have the expected types and allowed values before updating the database.