Sub topic 9
Keeping server code on the server
This chapter assumes you have read the chapters on loaders and actions, and that you know basic Node.js, TypeScript, and how bundlers produce separate browser and server builds. You will learn which code in a route module runs where, how the .server naming convention protects secrets, and which mistakes leak server code into the browser.
Why the boundary matters
In framework mode, one route module file can contain code for two environments. The browser needs the default component. The server runs the loader and action. The build tool splits the file into a server bundle and a client bundle, and it removes loader and action from the client bundle.
That removal works for code that only a loader or action uses. It does not cover everything. If a helper module with database credentials is also imported by a component, it ends up in the browser bundle. Anyone can read that bundle.
// app/routes/contacts/detail.tsx
import { db } from "~/db"; // risky: where else is this imported?
export async function loader() {
return { contacts: await db.contact.findMany() };
}
export default function Contacts() {
return <p>Hello</p>;
}In this file, db is only used inside loader, so the compiler can drop both the loader and the import from the client bundle. This works, but it relies on tree shaking, which depends on how the module is written. A module with side effects at import time, such as opening a connection, can survive. A .server file makes the rule explicit and checked.
Server-only modules with `.server`
Name a file something.server.ts, or put files in a folder named .server. React Router's build tool then refuses to include the module in the client bundle. If client code imports it, the build fails with an error instead of silently shipping the code.
// app/contacts.server.ts
const contacts = new Map<string, { id: string; name: string }>();
export async function getContact(id: string) {
return contacts.get(id) ?? null;
}
export async function createContact(input: { name: string }) {
const id = crypto.randomUUID();
const contact = { id, ...input };
contacts.set(id, contact);
return contact;
}A loader imports it as usual:
import { data } from "react-router";
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw data("Contact not found", { status: 404 });
}
return { contact };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.contact.name}</h1>;
}The component only receives loaderData, which is plain data sent over the network. It never imports the module that produced it.
There are two forms of the convention.
| Convention | Example | Scope |
|---|---|---|
| File suffix | `app/session.server.ts` | One file |
| Directory | `app/.server/db/index.ts` | Every file in the folder |
| Client counterpart | `app/analytics.client.ts` | One file, browser only |
A .client module is the reverse. It is excluded from the server bundle, which is useful for code that touches window at import time.
How the split works
The server build renders the page to HTML and answers data requests. The client build hydrates that HTML and handles navigation.
What counts as server-only
Treat these as server-only and keep them in .server files:
- Database clients and queries.
- Secret keys and anything read from
process.envthat is not meant to be public. - Session helpers that use secrets, such as
createCookieSessionStorage. - Node-only APIs such as
fsandchild_process. - Large server-side libraries, such as an image processor, that would bloat the browser bundle.
The session module from the sessions chapter follows this rule:
// app/sessions.server.ts
import { createCookieSessionStorage } from "react-router";
export const { getSession, commitSession, destroySession } =
createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
sameSite: "lax",
secrets: [process.env.SESSION_SECRET!],
secure: process.env.NODE_ENV === "production",
},
});If a component imported this file, the build would stop, and the cookie signing secret would not reach the browser.
Common errors
Importing a server module from a component
The build reports that a .server module cannot be imported into client code. The fix is to move the work into a loader or action and pass the result as props. Do not rename the file to remove .server, because that disables the check and ships the code.
Leaking secrets through loader data
The .server rule protects imports. It does not inspect what you return. Whatever a loader returns is serialized into the HTML and into data responses.
// Wrong: returns the whole row, including a password hash
export async function loader() {
return { user: await getUserRow() };
}
// Better: return only the fields the UI needs
export async function loader() {
const user = await getUserRow();
return { user: { id: user.id, name: user.name } };
}Reading environment variables in components
A component runs in the browser, where process.env has no server values. Read variables in a loader and return the safe ones. For values that must be public, use the build tool's public variable mechanism and keep secrets out of it.
Side effects in shared modules
A module imported by both components and loaders runs in both environments. Avoid creating connections or reading secrets at the top level of such a module. Move that code into a .server file.
Checking your boundary
Run a production build and look at the client output. If a secret value or a database library shows up in the files under build/client, a module is being shared where it should not be. Search the output for a string you know is only on the server.
npm run build
grep -r "SESSION_SECRET" build/client || echo "not found in client bundle"An empty result confirms that this one string is absent. It does not prove the whole bundle is clean, so also review which modules your components import.
Exercise
A component in app/routes/profile.tsx imports getUser from ~/users.server. What happens at build time, and what is the correct fix?
Show answer
The build fails because client code imports a .server module. Fix it by calling getUser inside the route's loader, returning only the fields the UI needs, and reading them in the component from loaderData. Renaming the file to drop .server would hide the error and ship the code to the browser.
Exercise
A loader returns { user }, where user is a full database row with a passwordHash field. The helper is in a .server file. Is the hash safe? Why or why not?
Show answer
No. The .server convention only blocks imports into client code. The loader's return value is serialized into the HTML and data responses, so the hash is sent to the browser. Return only the needed fields, for example { id: user.id, name: user.name }.