Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 72 ยท Server and Client Components

Keeping Server Code on the Server

Stop secrets and server logic from reaching the browser in Next.js: the server-only and client-only packages, NEXT_PUBLIC_ variables, taint APIs and context providers.

The most important security rule in a full-stack framework is also the easiest to break by accident: code that runs in the browser is public. Anyone can open the developer tools, read your JavaScript and see every string in it. If an API key, a database password or a pricing rule ends up in a Client Component's module graph, it ends up on every visitor's machine.

In the App Router you write server and client code in the same project, often in neighboring files, so mistakes are plausible. A helper that reads a secret is imported by a component that later gains "use client", and suddenly the helper ships. This lesson shows the tools for preventing that: the server-only and client-only packages, the NEXT_PUBLIC_ prefix for environment variables, a few habits for what to pass as props, and the standard trick for using context providers without turning the app into a client bundle. The real framework cannot run on this site, so its code is read-only; the two runnable examples are Node.js stand-ins for the build checks.

Four safety nets

server-only Build fails if client code imports the module.
client-only The reverse, for code that needs the browser.
NEXT_PUBLIC_ The only env vars that reach the browser.
Taint APIs Experimental flags for values that must not cross.

Use them together with careful props.

1 / 2

The server-only package

Install the tiny server-only package and import it at the top of any module that must never run in the browser. The import does nothing at runtime on the server. Its job is to break the build if the module ever ends up in the client module graph.

TypeScript
// lib/data.ts (read-only)
import "server-only";

export async function getUserByToken(token: string) {
  const res = await fetch("https://internal-api.example.com/users", {
    headers: { Authorization: `Bearer ${process.env.INTERNAL_API_KEY}` },
  });
  return res.json();
}

If a Client Component imports lib/data.ts, directly or through a chain of other modules, Next.js fails the build and points out the import. That is far better than discovering the leak in production. Put the import in every data-access module, in every file that reads a secret, and in helpers that sign tokens or talk to a payment API.

client-only is the mirror image. Import it in a module that reads window, localStorage or uses browser-only libraries, and the build fails if a Server Component pulls it in.

TypeScript
// lib/analytics.ts (read-only)
import "client-only";

export function track(event: string) {
  window.dispatchEvent(new CustomEvent("analytics", { detail: event }));
}

Trying it: a build check that follows imports

The stand-in below models how server-only works. It builds a small module graph, starts from each module that has "use client", follows every import, and reports any module marked server-only that it reaches, together with the import chain. This is a teaching model of the check; the real one runs inside the bundler.

Node.js Find the leak in the import chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server-only lib/data.ts is imported by the Server Component page, which is fine. The problem is lib/session.ts, which looks harmless but imports the database module, and like-button.tsx imports it. The chain makes the cause obvious. Remove the dependency, or move the logic into a Server Component or a Server Action.

Environment variables and NEXT_PUBLIC_

Environment variables follow a simple rule. Variables whose names start with NEXT_PUBLIC_ are inlined into the JavaScript at build time and are available in the browser. Everything else is available only on the server.

Terminal
# .env.local (read-only)
DATABASE_URL=postgres://user:secret@localhost/app
STRIPE_SECRET_KEY=sk_test_example
NEXT_PUBLIC_ANALYTICS_ID=G-EXAMPLE123
TSX
// read-only
// Server code: all three are available
const url = process.env.DATABASE_URL;

// Client Component: only the NEXT_PUBLIC_ one has a value
const id = process.env.NEXT_PUBLIC_ANALYTICS_ID; // inlined as "G-EXAMPLE123"
const key = process.env.STRIPE_SECRET_KEY; // not available in the browser

Two details matter. "Inlined" is literal: the bundler replaces the expression process.env.NEXT_PUBLIC_ANALYTICS_ID with the string value while building, so the value is fixed at build time and a change needs a rebuild. And because the replacement looks for that exact expression, dynamic access such as process.env[name] does not work in client code.

Never put a secret in a NEXT_PUBLIC_ variable. The name tells Next.js to publish it. A publishable key for a payment provider is fine; a secret key is not. The second TryIt simulates the build step and shows what the same code does on each side. The browser has no real environment: private values simply come back as nothing.

Node.js What does each side see?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server sees both variables, the browser bundle contains only the public id, and the private key is undefined there. If you rename the variable to NEXT_PUBLIC_STRIPE_SECRET_KEY, the program would flag no leak by its own check, because the name says "public"; the protection is entirely in your naming discipline and code review, which is why the prefix deserves respect.

What you pass as props is public too

A Server Component can read a secret safely, but if it passes the secret, or an object that contains it, as a prop to a Client Component, the value is written into the RSC payload and sent to the browser. Think of every prop as a public field.

TSX
// read-only
// Risky: user includes passwordHash, which now travels to the browser
const user = await db.user.findUnique({ where: { id } });
return <Profile user={user} />;

// Better: pass a small data transfer object with only what the UI needs
return <Profile name={user.name} avatarUrl={user.avatarUrl} />;

Building a small object for each client component, often called a DTO, is the habit that prevents this class of leak. Data Access Layers and ORMs shows a clean place to do it.

As an extra safety net, React ships experimental taint APIs (experimental_taintObjectReference and experimental_taintUniqueValue) that you can use to mark an object or a value as not allowed to pass into the client. They are opt-in through a Next.js experimental flag and should be treated as a backstop, not as a replacement for careful props.

Context providers without a client layout

Context needs a Client Component, but your root layout should stay on the server. The standard approach is a small wrapper file that holds the provider and accepts children.

TSX
// app/providers.tsx (read-only)
"use client";

import { createContext, useState } from "react";

export const ThemeContext = createContext<{ theme: string; setTheme: (t: string) => void } | null>(null);

export default function Providers({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState("light");
  return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>;
}
TSX
// app/layout.tsx (read-only): still a Server Component
import Providers from "./providers";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Thanks to the children pattern from Composing Server and Client Components, the pages inside <Providers> remain Server Components. Render providers as deep in the tree as they are needed; a provider that only the checkout needs belongs in the checkout layout, not the root.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does importing the server-only package in a module do?

    server-only is a guard: it does nothing on the server, but breaks the build if the module is pulled into code that runs in the browser.
  2. 2. Which environment variable is available in a Client Component?

    Only variables with the NEXT_PUBLIC_ prefix are inlined into the browser bundle. All others stay on the server.
  3. 3. Why do NEXT_PUBLIC_ values need a rebuild to change?

    The bundler inlines the value in place of the process.env expression, so the built JavaScript contains the old value until you build again.
  4. 4. A Server Component fetches a user record and passes it whole to a Client Component. What is the risk?

    Props are part of the RSC payload. Pass only the fields the UI needs, for example through a small DTO.

Summary

  • Import server-only in modules that must stay on the server (data access, secrets, token signing); client-only guards the reverse.
  • Only NEXT_PUBLIC_ variables reach the browser, and their values are inlined at build time, so never put a secret in one.
  • Everything passed as a prop to a Client Component is public; send small DTOs, not whole records.
  • Experimental taint APIs are an extra safety net, not a replacement for careful props.
  • Wrap context providers in a client file that accepts children, so layouts and pages stay Server Components.

Next: Inside the RSC Payload