| | |

React Server Components 23 🧬 Security Boundaries — Avoiding accidental data leaks through props

⏱️ Estimated read: 14 min | |

The props that cross the Server-to-Client boundary are not private. React serializes them into the RSC payload that the browser receives, and the browser can inspect that payload in the network tab, in the dev tools, and in the source of the page . The security failure is rarely a developer typing password={secret} on purpose. It is a Server Component that fetches a full user record or a configuration object for its own server-side use, then forwards the entire object to a Client Component because the component also happens to need one or two fields from it . The object crosses the boundary in full, and every field it contains is serialized, whether the Client Component reads it or not .

Key point: A value being “computed on the server” does not make it safe to send to the client. The boundary is the serialization point. What crosses it is data, and data is visible to anyone who receives the payload. The discipline is narrowing: pass only the fields the Client Component actually renders, never the full object that happens to contain them.


Why the props boundary leaks

The whole-object forwarding problem. A Server Component fetches const user = await db.user.findUnique(...). The user object contains name, email, passwordHash, stripeCustomerId, and internalNotes. The Client Component needs name. The developer writes <Profile user={user} />. The entire object is serialized into the RSC payload. The passwordHash is in the browser, even though the Client Component never reads it . The fix is not a security review of the Client Component; it is a change to what the Server Component passes: <Profile name={user.name} />.

The unused prop still serializes. A prop that the Client Component accepts but does not render is still serialized. The serialization happens at the boundary, not at the render. A Client Component with a secret prop that it ignores in its JSX still receives the secret in its props object, and that props object is in the payload . The absence of the value in the rendered HTML does not mean the absence of the value in the browser.

The "use client" file’s prop audit. Every exported component in a "use client" file should be reviewed for the shape of its props. A prop typed as a full User object is a prop that accepts every field the User type contains. A prop typed as { name: string } accepts only the name. The type is the contract, and the contract determines what the parent is allowed to pass. A narrow type prevents the whole-object forwarding bug at the type level .

The trade-off. Narrowing props requires more work in the Server Component. The developer must destructure the object and pass individual fields rather than passing the object. The work is small, but it is work, and the shortcut of passing the whole object is tempting because it compiles and the Client Component renders correctly. The security failure is silent: no error, no warning, no visible change in the UI. The leak is only visible in the payload.


a. The narrowing pattern and the DTO

The correct pattern is to return a Data Transfer Object (DTO) from the data access layer: an object that contains only the fields the caller needs, not the full database record.

// lib/users.ts — the data access layer returns a narrow DTO
import "server-only";

export async function getProfileDTO(id: string) {
  const user = await db.user.findUnique({ where: { id } });

  // Return only the fields the client needs.
  // The passwordHash, email, and internal notes stay on the server.
  return {
    name: user.name,
    avatarUrl: user.avatarUrl,
  };
}
// app/profile/page.tsx — the Server Component passes only the DTO
import { getProfileDTO } from "@/lib/users";
import { Profile } from "./profile";

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const profile = await getProfileDTO(id);

  // The Profile component receives name and avatarUrl.
  // It does not receive the full user record.
  return <Profile name={profile.name} avatarUrl={profile.avatarUrl} />;
}
// app/profile/profile.tsx — the Client Component accepts only what it renders
"use client";

export function Profile({ name, avatarUrl }: { name: string; avatarUrl: string }) {
  return (
    <div>
      <img src={avatarUrl} alt={name} />
      <h1>{name}</h1>
    </div>
  );
}

The DTO is the boundary. The data access layer returns an object whose shape is defined by what the client needs, not by what the database contains. The Server Component passes individual fields, and the Client Component’s props type matches the fields it renders . The passwordHash never enters the payload because it never leaves the data access layer.


b. The taint API as a safety net

React provides an experimental API called experimental_taintUniqueValue that marks a specific value as sensitive. Once tainted, React throws an error if the value is passed to a Client Component or a Server Function. The API is a safety net, not a replacement for narrowing: it catches the accidental leak, but the correct design is still to not pass the value at all .

// lib/taint.ts — taint the secret at the server entry point
import "server-only";
import { experimental_taintUniqueValue } from "react";

experimental_taintUniqueValue(
  "Do not pass the API password to the client. " +
    "Instead do all fetches on the server.",
  process,
  process.env.API_PASSWORD
);

The taint is registered once, on the server, before any component renders. If a Server Component later writes <ClientComponent password={process.env.API_PASSWORD} />, React throws during rendering. The error is hard and immediate, not a silent serialization . The API is experimental, and it is only available in Server Components. It is the fallback for codebases that cannot yet guarantee the narrowing pattern everywhere, not the primary defense.

The primary defense remains the DTO and the narrow prop type. The taint API is the second layer, for the case where the first layer fails.


Complete Example Session

// ============================================
// PART 1: THE LEAK (WHOLE-OBJECT FORWARDING)
// ============================================

// app/user/page.tsx — the Server Component fetches the full record
import { db } from "@/lib/db";

export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await db.user.findUnique({ where: { id } });

  // ❌ The entire user object is serialized into the payload.
  // passwordHash, email, stripeCustomerId, internalNotes all cross.
  return <UserCard user={user} />;
}

// app/user/user-card.tsx — the Client Component only reads name
"use client";

export function UserCard({ user }: { user: User }) {
  return <h1>{user.name}</h1>;
}

// ============================================
// PART 2: THE FIX (NARROW PROPS)
// ============================================

// app/user/page.tsx — the Server Component passes only what is needed
export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await db.user.findUnique({ where: { id } });

  // ✅ Only the name crosses the boundary.
  return <UserCard name={user.name} />;
}

// app/user/user-card.tsx — the Client Component accepts only the name
"use client";

export function UserCard({ name }: { name: string }) {
  return <h1>{name}</h1>;
}

// ============================================
// PART 3: THE DTO PATTERN
// ============================================

// lib/users.ts — the data access layer returns a DTO
import "server-only";

export async function getUserCardDTO(id: string) {
  const user = await db.user.findUnique({ where: { id } });

  // The DTO is defined by the client's needs, not the database schema.
  return { name: user.name };
}

// app/user/page.tsx — the Server Component uses the DTO
import { getUserCardDTO } from "@/lib/users";

export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const dto = await getUserCardDTO(id);
  return <UserCard name={dto.name} />;
}

// ============================================
// PART 4: THE UNUSED PROP LEAK
// ============================================

// app/user/user-card.tsx — a prop that is not rendered is still serialized
"use client";

export function UserCard({ name, email }: { name: string; email: string }) {
  // ❌ email is not rendered, but it is still in the props object
  // and therefore in the RSC payload.
  return <h1>{name}</h1>;
}

// The fix is to remove the email prop from the component signature.
// A prop that the component does not use should not be accepted.

// ============================================
// PART 5: THE TAINT SAFETY NET
// ============================================

// lib/taint.ts — taint the secret once at the server entry
import "server-only";
import { experimental_taintUniqueValue } from "react";

experimental_taintUniqueValue(
  "Do not pass the API password to the client.",
  process,
  process.env.API_PASSWORD
);

// If any Server Component later writes:
// <ClientComponent password={process.env.API_PASSWORD} />
// React throws during rendering.

// ============================================
// PART 6: THE SERVER ACTION CLOSURE CAVEAT
// ============================================

// Server Action closures are encrypted in transit.
// But .bind() values are NOT encrypted.
// They are visible in the client payload.

// app/post/page.tsx — a Server Action with a bound value
export default async function PostPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;

  async function deletePost() {
    "use server";
    await db.post.delete({ where: { id } });
  }

  // The bound id is visible in the client payload.
  // If the id is sensitive, do not bind it.
  // Pass it from the form data instead and re-validate on the server.
  return <DeleteButton action={deletePost} />;
}

// ============================================
// PART 7: THE PROP AUDIT CHECKLIST
// ============================================

// For every "use client" component:
// [ ] The props type is narrow, not a full database object.
// [ ] The prop names do not include token, secret, password, key.
// [ ] The component renders every prop it accepts.
// [ ] The parent passes individual fields, not the whole object.

// ============================================
// PART 8: THE DATA ACCESS LAYER
// ============================================

// lib/dal.ts — the chokepoint for data access
import "server-only";

export async function getProfileDTO(slug: string) {
  const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}`;
  const userData = rows[0];

  // Return only the fields the caller needs.
  // The passwordHash, email, and internal IDs stay in this function.
  return {
    username: userData.username,
    avatarUrl: userData.avatarUrl,
  };
}

// The "server-only" import causes a build error if any Client Component
// imports this module. The guard protects the module, not the call site.

// ============================================
// PART 9: THE SERIALIZATION CHECK
// ============================================

// Props must be serializable.
// A function, a class instance, or a symbol cannot cross the boundary.
// A Date, a Map, a Set, a plain object, and an array can.
// A React element can cross as a child (the composition pattern).

// ============================================
// PART 10: THE VERIFICATION
// ============================================

// [ ] Every Client Component's props are audited for full-object types.
// [ ] Every Server Component that fetches data returns a DTO.
// [ ] The data access layer uses "server-only".
// [ ] The taint API is used for secrets that cannot be narrowed.
// [ ] The .bind() values on Server Actions are audited.

The ten parts covered the leak, the fix, the DTO, the unused prop, the taint API, the Server Action closure, the audit checklist, the data access layer, the serialization check, and the verification. The through-line is that the boundary is a serialization point, and the only safe prop is the one the client actually needs.


Quick Reference

The narrowing rules

PatternSafe?Why
<Client user={user} />❌Full object, every field serialized
<Client name={user.name} />✅Only the field the client needs
<Client config={config} />❌Full config, secrets included
<Client version={config.version} />✅Narrowed to one field

The audit checklist

CheckQuestion
Prop typeIs the type narrow, not a full database object?
Prop nameDoes it contain token, secret, password, key?
Prop usageDoes the component render the prop?
ParentDoes it pass individual fields or the whole object?

The guards

GuardScopeWhat it prevents
import "server-only"The moduleThe module entering the client graph
experimental_taintUniqueValueThe specific valueThe value crossing the boundary
DTOThe data access layerThe full record leaving the server

Best Practices

✅ Do This:

// Pass narrow props
<Profile name={user.name} avatarUrl={user.avatarUrl} />       // ✅

// Return a DTO from the data access layer
return { name: user.name, avatarUrl: user.avatarUrl };         // ✅

// Use server-only in the data access layer
import "server-only";                                          // ✅

// Taint the secret as a safety net
experimental_taintUniqueValue("Do not pass", process, secret); // ✅

❌ Don’t Do This:

// Pass the full object
<Profile user={user} /> // every field serialized               // ❌

// Accept a prop the component does not render
function Profile({ name, email }: { name: string; email: string }) { // ❌

// Import a server-only module in a Client Component
import { db } from "@/lib/db"; // build error or leak           // ❌

Common Pitfalls

PitfallWhy It HappensFix
passwordHash in the browserFull user object passed to a Client ComponentPass only name
A prop is not rendered but is still in the payloadThe component accepts the propRemove the prop from the signature
A secret is in the client bundleThe secret was passed as a propNarrow the prop or taint the value
.bind() value is visibleServer Action .bind() values are not encryptedPass the value from form data and re-validate

Real-World Examples

1. The leak

<Profile user={user} /> // passwordHash, email, ssn all cross

2. The fix

<Profile name={user.name} /> // only the name crosses

3. The DTO

return { name: user.name, avatarUrl: user.avatarUrl };

4. The narrow prop type

function Profile({ name }: { name: string }) { return <h1>{name}</h1>; }

5. The unused prop

function Profile({ name, email }: { name: string; email: string }) { /* email unused */ } // ❌

6. The server-only guard

import "server-only"; // build error if a Client Component imports the module

7. The taint API

experimental_taintUniqueValue("Do not pass", process, process.env.SECRET);

8. The .bind() caveat

<button action={deletePost.bind(null, id)}>Delete</button> // id is visible

9. The composition pattern

<ClientWrapper><ServerChart data={data} /></ClientWrapper> // chart code stays on server

10. The audit

// Every "use client" prop is checked for full-object types

Visual

The Serialization Boundary

┌──────────────────────────────────────────────────────────────┐
│  WHAT CROSSES THE BOUNDARY                                    │
│                                                              │
│  Server Component                                            │
│  ┌──────────────────────────────────────────────┐           │
│  │ const user = await db.user.findUnique()      │           │
│  │ // { name, email, passwordHash, ssn }        │           │
│  └──────────────────────┬───────────────────────┘           │
│                         │                                    │
│         ┌───────────────┴───────────────┐                   │
│         │                               │                   │
│         ▼                               ▼                   │
│  ❌ <Client user={user} />        ✅ <Client name={user.name} />
│  ┌─────────────────────┐       ┌─────────────────────┐     │
│  │ Payload contains:   │       │ Payload contains:   │     │
│  │ name                │       │ name                │     │
│  │ email               │       │                     │     │
│  │ passwordHash        │       │                     │     │
│  │ ssn                 │       │                     │     │
│  └─────────────────────┘       └─────────────────────┘     │
│                                                              │
│  The full object is visible in the browser's network tab.   │
│  The narrow prop is the only field the client receives.     │
└──────────────────────────────────────────────────────────────┘

The DTO Chokepoint

┌──────────────────────────────────────────────────────────────┐
│  THE DATA ACCESS LAYER NARROWS                               │
│                                                              │
│  Database                                                    │
│  ┌─────────────────────┐                                    │
│  │ Full user record    │                                    │
│  │ name, email,        │                                    │
│  │ passwordHash, ssn   │                                    │
│  └──────────┬──────────┘                                    │
│             │                                                │
│             ▼                                                    │
│  ┌─────────────────────┐                                    │
│  │ DAL: getProfileDTO  │  Returns only name, avatarUrl      │
│  │ "server-only"       │  The other fields never leave     │
│  └──────────┬──────────┘  this function                     │
│             │                                                │
│             ▼                                                    │
│  ┌─────────────────────┐                                    │
│  │ Server Component    │  Passes name and avatarUrl         │
│  └──────────┬──────────┘                                    │
│             │                                                │
│             ▼                                                    │
│  ┌─────────────────────┐                                    │
│  │ Client Component    │  Receives only the narrow DTO      │
│  └─────────────────────┘                                    │
└──────────────────────────────────────────────────────────────┘

The Taint Safety Net

┌──────────────────────────────────────────────────────────────┐
│  TAINTING THE SECRET                                         │
│                                                              │
│  Server entry:                                               │
│  ┌─────────────────────┐                                    │
│  │ taintUniqueValue(   │                                    │
│  │   "Do not pass",    │                                    │
│  │   process,          │                                    │
│  │   process.env.SECRET│                                    │
│  │ )                   │                                    │
│  └──────────┬──────────┘                                    │
│             │                                                │
│             ▼                                                    │
│  Later, in a Server Component:                               │
│  ┌─────────────────────┐                                    │
│  │ <Client            │                                    │
│  │   secret={process. │──── React throws                   │
│  │   env.SECRET} />    │     during render                  │
│  └─────────────────────┘                                    │
│                                                              │
│  The leak becomes a hard error, not a silent serialization. │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
The leakFull objects passed as props to Client Components
The fixNarrow props, only the fields the client renders
The DTOData access layer returns only the fields the caller needs
The guardimport "server-only" protects the module
The safety netexperimental_taintUniqueValue throws on leak
The unused propA prop that is not rendered is still serialized
The .bind() caveatBound Server Action values are not encrypted

Key takeaways:

  • Props cross the boundary as serialized data. The browser receives the payload, and the payload contains every prop value. A value being “computed on the server” does not make it safe to send to the client. The only safe prop is the one the client actually needs .
  • Whole-object forwarding is the common failure mode. A Server Component fetches a full record and passes the object to a Client Component that reads one field. The entire record is serialized, including fields the client never reads. The fix is to pass the individual field, not the object .
  • The DTO is the chokepoint. The data access layer returns an object whose shape is defined by the client’s needs, not the database schema. The sensitive fields never leave the data access layer because the DTO does not include them .
  • An unused prop is still a leak. A Client Component that accepts a secret prop and does not render it still receives the secret in its props, and the props are serialized. The prop must be removed from the component’s signature, not just ignored in the JSX .
  • The taint API is a safety net, not the primary defense. experimental_taintUniqueValue throws when a tainted value crosses the boundary. It catches the accidental leak, but the correct design is still to narrow the props so the value never reaches the boundary .

Remember: The Server-to-Client boundary is a serialization boundary, and serialization is publication. What crosses the boundary is visible to the browser, to the network tab, and to anyone who inspects the payload. The discipline is not to trust the Client Component to ignore what it does not need; the discipline is to never send it in the first place. The DTO narrows the data at the source. The narrow prop type narrows it at the boundary. The taint API catches the case where the narrowing failed. The leak is silent by default, and the only defense is the discipline of passing exactly what the client renders, and nothing more.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!