Sub topic 9
Keeping server code on the server
This chapter assumes you know React Router loaders, the .server file naming idea, and basic Node.js environment variables. It covers how framework mode separates server and browser code, and the mistakes that break that separation.
Why the boundary exists
A route module can export loader, action, and a default component. The component runs in the browser. The loader and action run only on the server. The build removes loader and action from the browser bundle, along with imports used only by them.
That works for simple cases. It can fail when a helper module is imported from both sides. If the browser bundle pulls in a database client or a secret, you leak code or crash at runtime.
The `.server` and `.client` suffixes
Name a file something.server.ts and the build guarantees it never reaches the browser. If client code imports it, the build fails with an error. A .server directory has the same effect.
// app/contacts.server.ts
import { db } from "./db.server";
export async function getContact(id: string) {
return db.contact.findUnique({ where: { id } });
}A loader can import this file safely:
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
return { contact: await getContact(params.contactId) };
}The .client suffix is the mirror image. It marks modules that touch window or other browser-only APIs, so they are not evaluated during server rendering.
What crosses the boundary
Only the loader's return value goes to the browser. It is serialized and sent with the page. Return only the fields the UI needs.
export async function loader({ params }: Route.LoaderArgs) {
const user = await getUser(params.userId);
return { name: user.name, email: user.email };
}Returning the whole user object could expose a password hash or an internal flag.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Importing `db.ts` in a component | Database code in the browser bundle | Rename to `db.server.ts` |
| Reading `process.env.SECRET` in a component | `undefined` in the browser, or a leaked value if inlined | Read it only in server files |
| Returning a full database row | Private fields sent to the client | Select fields explicitly |
| Using `window` at module top level | Server render crashes | Use a `.client` module or `useEffect` |
Exercise
A component imports getContact from ~/contacts.server, and the build fails. What is the correct fix?
Show answer
Move the call into a loader, which runs only on the server, and read the data in the component from loaderData. The build error is the .server guard working as intended.
Exercise
Why should a loader return { name, email } instead of the whole user record?
Show answer
The loader's return value is serialized and sent to the browser. Returning the whole record can expose private fields such as a password hash.