| | |

React Server Components 24 🧬 Environment Poisoning — The server-only package and secret hygiene

⏱️ Estimated read: 13 min | |

The server-only package is a one-line import with a build-time consequence: if any module in the client bundle graph imports the file that contains it, the build fails. The package does not encrypt anything, does not sanitize anything, and does not run at runtime. It is a marker that the bundler reads, and the bundler’s response is a hard error . The error is the point. A secret that reaches the client bundle through an accidental import is a silent leak; the server-only import converts that silence into a build failure.

The failure mode it addresses is not the deliberate passing of a secret as a prop. It is the accidental import chain. A Client Component imports a utility from @/lib/utils, and @/lib/utils happens to import @/lib/db for a function that the Client Component never calls. The bundler follows the import, pulls @/lib/db into the client graph, and the process.env.DATABASE_URL read at the top of that module is inlined into the client bundle. The Client Component did not ask for the database client; it asked for a utility. The import chain delivered the secret anyway. The server-only import at the top of @/lib/db stops the build at the moment the chain is formed .

Key point: import 'server-only' protects the module it is declared in, not the call site and not the sibling file. A data-access module with the import is protected; a sibling module in the same directory without the import is not. The guard is per-file, and the discipline is to put it in every file that reads a secret or touches a server-only resource.


Why the import is the mechanism

The build-time error, not the runtime error. The server-only package works because Next.js and other RSC-aware bundlers recognize the package name and treat it as a marker. When a Client Component imports a module that contains import 'server-only', the bundler fails the build with an error that points to the import chain . The error is immediate and visible. A runtime error would be worse: the secret would already be in the bundle, and the error would only fire when the code path executes. The build-time error prevents the leak from shipping.

The per-module scope. The guard protects the file it is in. If lib/db.ts has the import and lib/auth.ts does not, a Client Component can import lib/auth.ts without a build error. If lib/auth.ts reads process.env.JWT_SECRET, the secret is in the client bundle. The guard in lib/db.ts does not cover lib/auth.ts . The discipline is to put the import in every file that reads an environment secret, every file that instantiates a database client, and every file that contains server-only logic.

The taint API is a separate layer. The server-only package prevents the module from entering the client graph. The taint API (experimental_taintUniqueValue) prevents a specific value from crossing the serialization boundary even if the module is available on the server . The two mechanisms address different leaks. The server-only import stops the import chain; the taint API stops the prop. A codebase that uses both has two layers of defense against the accidental leak.

The trade-off. The server-only import adds a dependency and a line of boilerplate to every protected file. The dependency is tiny, and the line is trivial. The cost is the discipline: every new data-access file needs the import, and a developer who forgets it creates an unprotected file that compiles and runs until the secret is in the client bundle. The guard is only as strong as the consistency of its application.


a. The basic pattern and the data access layer

The canonical placement is at the top of the data access layer module, before any import that reads a secret or creates a client.

// lib/db.ts
import "server-only";

import { PrismaClient } from "@prisma/client";

// The Prisma client reads DATABASE_URL.
// If a Client Component imports this module,
// the build fails before the client is created.
const db = new PrismaClient();

export { db };
// lib/auth.ts
import "server-only";

import jwt from "jsonwebtoken";

const JWT_SECRET = process.env.JWT_SECRET!;

export function verifyToken(token: string) {
  return jwt.verify(token, JWT_SECRET);
}

The import is the first line of the file, before the other imports. The placement is conventional and it makes the guard visible in a code review. The bundler does not care about the order, but the developer who reads the file sees the guard immediately .

The data access layer is the highest-value place for the guard because it is the chokepoint for the secrets. A module that reads process.env.DATABASE_URL or process.env.JWT_SECRET is a module that must never enter the client bundle. The server-only import is the enforcement.


b. The barrel file trap and the per-file audit

A barrel file (lib/index.ts that re-exports from other modules) is a common source of accidental leaks. The barrel file re-exports the data access module, and a Client Component imports the barrel file for an unrelated utility. The bundler follows the re-export, and the data access module enters the client graph .

// lib/index.ts — the barrel file
export { formatDate } from "./format";
export { db } from "./db"; // ❌ the server-only module is re-exported
// app/components/Billing.tsx — a Client Component
"use client";

import { formatDate } from "@/lib"; // the barrel pulls db into the graph

export function Billing() {
  return <div>{formatDate(new Date())}</div>;
}

The Client Component imports formatDate from the barrel, and the barrel re-exports db. The bundler follows the re-export and includes lib/db.ts in the client graph. The server-only import in lib/db.ts causes the build to fail, which is the correct outcome: the leak is caught. The fix is to not re-export server-only modules from a barrel that client code imports. The barrel file should export only client-safe utilities, and the server-only modules should be imported directly by the Server Components that need them .

The per-file audit is the discipline that makes the guard effective. Every file that reads a secret or creates a server client needs the import. A file that forgets it is a file that can leak. The audit is not a one-time task; it is a review checklist for every new data-access module.


Complete Example Session

// ============================================
// PART 1: THE UNPROTECTED MODULE
// ============================================

// lib/db.ts — no server-only import
import { PrismaClient } from "@prisma/client";

// DATABASE_URL is inlined into the client bundle
// if this module enters the client graph.
const db = new PrismaClient();

export { db };

// ============================================
// PART 2: THE ACCIDENTAL IMPORT
// ============================================

// app/components/UserCard.tsx — a Client Component
"use client";

// The import chain pulls lib/db.ts into the client graph.
import { formatDate } from "@/lib";

export function UserCard({ createdAt }: { createdAt: Date }) {
  return <time>{formatDate(createdAt)}</time>;
}

// The build succeeds. The DATABASE_URL is in the client bundle.

// ============================================
// PART 3: THE GUARD
// ============================================

// lib/db.ts — with server-only
import "server-only";

import { PrismaClient } from "@prisma/client";

const db = new PrismaClient();

export { db };

// The same Client Component import now causes a build error.
// The error points to the import chain:
// UserCard.tsx → lib/index.ts → lib/db.ts

// ============================================
// PART 4: THE BARREL FILE FIX
// ============================================

// lib/index.ts — client-safe barrel
export { formatDate } from "./format";
// export { db } from "./db"; // ❌ removed

// app/components/UserCard.tsx — the import no longer leaks
import { formatDate } from "@/lib";

// ============================================
// PART 5: THE TAINT API LAYER
// ============================================

// lib/taint.ts — taint the secret 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
);

// The server-only import protects the module.
// The taint API protects the value if a Server Component
// tries to pass it as a prop.

// ============================================
// PART 6: THE PER-FILE AUDIT
// ============================================

// ✅ lib/db.ts          — import "server-only"
// ✅ lib/auth.ts        — import "server-only"
// ✅ lib/stripe.ts      — import "server-only"
// ❌ lib/utils.ts       — no import, no secrets
// ❌ lib/format.ts      — no import, no secrets

// The audit checks every file that reads process.env
// or creates a server client.

// ============================================
// PART 7: THE NEXT_PUBLIC_ BOUNDARY
// ============================================

// Next.js inlines NEXT_PUBLIC_ variables into the client bundle.
// A variable without the prefix stays on the server.
//
// .env
// DATABASE_URL=postgres://...        ← server-only
// NEXT_PUBLIC_ANALYTICS_ID=abc123    ← client-visible
//
// The server-only import is the guard for the server-only file.
// The NEXT_PUBLIC_ prefix is the mechanism for the client-visible value.

// ============================================
// PART 8: THE BUILD ERROR
// ============================================

// When a Client Component imports a server-only module:
// Build error: "You're importing a component that needs server-only.
// That only works in a Server Component but one of its parents
// is marked 'use client'."
//
// The error is the guard working. The fix is to remove the import
// from the client graph, not to remove the server-only import.

// ============================================
// PART 9: THE SIBLING FILE TRAP
// ============================================

// lib/db.ts — has the guard
import "server-only";
export const db = new Database();

// lib/auth.ts — no guard, same directory
export const JWT_SECRET = process.env.JWT_SECRET;
export function verifyToken(token: string) { /* ... */ }

// A Client Component imports lib/auth.ts.
// The build succeeds because lib/auth.ts has no guard.
// The JWT_SECRET is in the client bundle.

// The fix: add the guard to lib/auth.ts.

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

// [ ] Every file that reads process.env has the import.
// [ ] Every file that creates a database client has the import.
// [ ] Every barrel file excludes server-only modules.
// [ ] The build fails when a Client Component imports a guarded module.
// [ ] The taint API is used for secrets that cannot be removed.

The ten parts covered the unprotected module, the accidental import, the guard, the barrel file fix, the taint layer, the per-file audit, the NEXT_PUBLIC_ boundary, the build error, the sibling file trap, and the verification. The through-line is that the guard is per-file, and the discipline is the consistency of its application.


Quick Reference

The guard

ItemValue
Importimport "server-only"
PlacementFirst line of the module
EffectBuild error if a Client Component imports the module
ScopeThe file it is declared in, not siblings
Packageserver-only

The boundary rules

RuleMechanism
Server-only moduleimport "server-only"
Server-only valueexperimental_taintUniqueValue
Client-visible variableNEXT_PUBLIC_ prefix
Server-only variableNo prefix (stays on server)

The audit checklist

CheckQuestion
Secret readDoes the file read process.env?
Client creationDoes the file create a database or API client?
Barrel exportIs the file re-exported from a client-safe barrel?
Sibling filesDo sibling files in the same directory also have the guard?

Best Practices

✅ Do This:

// Put the guard at the top of every server-only module
import "server-only";                                              // ✅

// Keep server-only modules out of client-safe barrels
export { formatDate } from "./format"; // no db re-export         // ✅

// Use the taint API for secrets that cross the prop boundary
experimental_taintUniqueValue("Do not pass", process, secret);    // ✅

❌ Don’t Do This:

// Assume the guard covers sibling files
// lib/auth.ts without the import is unprotected                   // ❌

// Re-export a server-only module from a barrel
export { db } from "./db"; // client import pulls db in            // ❌

// Rely on the guard alone for prop-level leaks
// The guard protects the module, not the serialized value.       // ❌

Common Pitfalls

PitfallWhy It HappensFix
Secret in the client bundleA sibling file lacks the guardAdd import "server-only" to every file that reads a secret
Build error after adding the guardA Client Component imports the guarded moduleRemove the import from the client graph
Barrel file pulls in the guardThe barrel re-exports a server-only moduleExclude the module from the barrel
Taint API does not fireThe value is derived from the tainted valueTaint the derived value separately

Real-World Examples

1. The guard

import "server-only";
export const db = new Database();

2. The sibling file

// lib/auth.ts — same guard
import "server-only";
export const JWT_SECRET = process.env.JWT_SECRET;

3. The barrel file

// Client-safe barrel
export { formatDate } from "./format";

4. The taint API

experimental_taintUniqueValue("Do not pass", process, secret);

5. The build error

You're importing a component that needs server-only.

6. The NEXT_PUBLIC_ variable

NEXT_PUBLIC_ANALYTICS_ID=abc123

7. The server-only variable

DATABASE_URL=postgres://...

8. The audit

// Every file with process.env has the guard

9. The sibling trap

// lib/db.ts has the guard; lib/auth.ts does not

10. The fix

// Add the guard to lib/auth.ts

Visual

The Guard’s Scope

┌──────────────────────────────────────────────────────────────┐
│  THE GUARD IS PER-FILE                                        │
│                                                              │
│  lib/                                                        │
│  ├── db.ts                                                   │
│  │   ┌─────────────────────┐                                │
│  │   │ import "server-only"│  ← GUARDED                    │
│  │   │ export const db     │                                │
│  │   └─────────────────────┘                                │
│  │                                                            │
│  ├── auth.ts                                                 │
│  │   ┌─────────────────────┐                                │
│  │   │ export const SECRET │  ← NOT GUARDED                 │
│  │   │ (no import)         │  ← LEAK RISK                   │
│  │   └─────────────────────┘                                │
│  │                                                            │
│  └── utils.ts                                                │
│      ┌─────────────────────┐                                │
│      │ export function fmt │  ← no secrets, no guard needed │
│      └─────────────────────┘                                │
│                                                              │
│  The guard in db.ts does not protect auth.ts.               │
└──────────────────────────────────────────────────────────────┘

The Import Chain

┌──────────────────────────────────────────────────────────────┐
│  HOW THE GUARD FIRES                                          │
│                                                              │
│  Client Component                                            │
│  ┌─────────────────────┐                                    │
│  │ import { fmt }      │                                    │
│  │ from "@/lib"        │                                    │
│  └──────────┬──────────┘                                    │
│             │                                                │
│             ▼                                                    │
│  Barrel file                                                 │
│  ┌─────────────────────┐                                    │
│  │ export { fmt }      │                                    │
│  │ export { db }       │  ← re-export                       │
│  └──────────┬──────────┘                                    │
│             │                                                │
│             ▼                                                    │
│  Guarded module                                              │
│  ┌─────────────────────┐                                    │
│  │ import "server-only"│  ← BUILD ERROR                     │
│  └─────────────────────┘                                    │
│                                                              │
│  The build fails at the guard.                              │
│  The secret never reaches the client bundle.                │
└──────────────────────────────────────────────────────────────┘

The Two Layers

┌──────────────────────────────────────────────────────────────┐
│  server-only AND TAINT API                                    │
│                                                              │
│  server-only                     Taint API                   │
│  ┌─────────────────────┐       ┌─────────────────────┐     │
│  │ Protects the module │       │ Protects the value  │     │
│  │ Build-time error    │       │ Render-time error   │     │
│  │ Stops the import    │       │ Stops the prop      │     │
│  │ chain               │       │ serialization       │     │
│  └─────────────────────┘       └─────────────────────┘     │
│                                                              │
│  The guard is the first layer.                              │
│  The taint API is the second.                               │
│  Neither is sufficient alone for every case.               │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Packageserver-only
Importimport "server-only"
EffectBuild error if a Client Component imports the module
ScopeThe file it is declared in
Sibling filesNot protected
Barrel filesCan pull the guarded module into the client graph
Taint APISeparate layer for value-level leaks
NEXT_PUBLIC_The only sanctioned client-visible variable prefix

Key takeaways:

  • import 'server-only' is a build-time guard, not a runtime check. It causes the build to fail if the module enters the client bundle graph. The failure is the point: a secret that reaches the client bundle through an accidental import is a silent leak, and the guard converts it into a visible error .
  • The guard is per-file, not per-directory. A file with the import is protected; a sibling file without it is not. The discipline is to put the import in every file that reads an environment secret or creates a server client .
  • Barrel files can defeat the guard. A barrel that re-exports a server-only module can pull it into the client graph when a Client Component imports the barrel for an unrelated utility. The guard catches the leak at build time, but the fix is to exclude server-only modules from client-safe barrels .
  • The taint API is a separate layer for value-level leaks. The server-only import protects the module; experimental_taintUniqueValue protects the value if a Server Component tries to pass it as a prop. The two mechanisms address different failure modes .
  • NEXT_PUBLIC_ is the only sanctioned path for a variable to reach the client. A variable without the prefix stays on the server. A variable with the prefix is inlined into the client bundle at build time. The prefix is the boundary marker, and the server-only import is the guard for the modules that read the non-prefixed variables .

Remember: The server-only package is a marker that the bundler reads. It does not encrypt, sanitize, or hide anything. It fails the build when a Client Component tries to import a module that is supposed to stay on the server. The failure is the protection. The discipline is to put the marker in every file that touches a secret, to keep those files out of client-safe barrels, and to audit the sibling files that the marker does not cover. The guard is only as strong as the consistency of its application.

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!