Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

import-protection.md

569 lines24.2 KB

1---
2id: import-protection
3title: Import Protection
4---
5​
6Import protection prevents server-only code from leaking into client bundles and client-only code from leaking into server bundles. It runs inside TanStack Start and is enabled by default.
7​
8## How It Works
9​
10TanStack Start builds your application for two environments: **client** and **server**. Some code should only run in one environment. Import protection checks every import in your source files during development and build, and either blocks or mocks imports that cross environment boundaries.
11​
12There are two ways an import can be denied:
13​
14- **File patterns** match on the resolved file path. By default, `*.server.*` files are denied in the client environment and `*.client.*` files are denied in the server environment.
15- **Specifier patterns** match on the raw import string. By default, `@tanstack/react-start/server` is denied in the client environment.
16​
17## Default Rules
18​
19Import protection is enabled out of the box with these defaults:
20​
21| Setting | Default |
22| ------------------ | ----------------------------------------------- |
23| `behavior` (dev) | `'mock'` -- warn and replace with a mock module |
24| `behavior` (build) | `'error'` -- fail the build |
25| `log` | `'once'` -- deduplicate repeated violations |
26| Scope | Files inside Start's `srcDirectory` |
27​
28**Client environment denials:**
29​
30- Files matching `**/*.server.*`
31- The specifier `@tanstack/react-start/server`
32- Excluded from file checks: `**/node_modules/**`
33​
34**Server environment denials:**
35​
36- Files matching `**/*.client.*`
37- Excluded from file checks: `**/node_modules/**`
38​
39By default, files inside `node_modules` are excluded from resolved-target deny checks via the `excludeFiles` option. This prevents false positives from third-party packages whose resolved filenames contain `.client.` or `.server.`. If you need to check third-party files, set `excludeFiles: []` on the relevant environment β€” see [Configuring Deny Rules](#configuring-deny-rules).
40​
41These defaults mean you can use the `.server.ts` / `.client.ts` naming convention to restrict files to a single environment without any configuration. To also deny entire directories (e.g. `server/` or `client/`), add them via `files` in your [deny rules configuration](#configuring-deny-rules) β€” for example `files: ['**/*.server.*', '**/server/**']` for the client environment.
42​
43## Type-Only Imports
44​
45Type-only imports and re-exports are ignored by import protection because they are erased from the runtime bundle and cannot leak environment-specific code.
46​
47```ts
48import type { User } from './db.server'
49import { type RequestHandler } from '@tanstack/react-start/server'
50​
51export type { User } from './db.server'
52```
53​
54Mixed imports still count when they include at least one runtime value. Split the type and value imports if only the type is safe to cross the environment boundary.
55​
56```ts
57// This is still checked because `getUsers` is a runtime value.
58import { type User, getUsers } from './db.server'
59```
60​
61## File Markers
62​
63You can explicitly mark a module as server-only or client-only by adding a side-effect import at the top of the file:
64​
65```ts
66// src/lib/secrets.ts
67import '@tanstack/react-start/server-only'
68​
69export const API_KEY = process.env.API_KEY
70```
71​
72```ts
73// src/lib/local-storage.ts
74import '@tanstack/react-start/client-only'
75​
76export function savePreferences(prefs: Record<string, string>) {
77 localStorage.setItem('prefs', JSON.stringify(prefs))
79```
80​
81When the plugin sees a marker import, it records the file as restricted. If that file is later imported from the wrong environment, the import is denied. Both markers in the same file is always an error.
82​
83Markers are useful when a file doesn't follow the `.server.*` / `.client.*` naming convention but still contains environment-specific code.
84​
85## Behavior Modes
86​
87The `behavior` option controls what happens when a violation is detected:
88​
89- **`'error'`** -- The build fails with a detailed error message. This is the default for production builds.
90- **`'mock'`** -- The import is replaced with a mock module that returns safe proxy values. A warning is logged but the build continues. This is the default during development.
91​
92Mock mode is useful during development because it lets you keep working even when your import graph has violations. The mock module returns a recursive Proxy, so any property access or function call on a mocked import returns another mock instead of crashing.
93​
94You can override the defaults:
95​
96<!-- ::start:tabs variant="bundler" -->
97​
98# Vite
99​
100```ts title="vite.config.ts"
101import { defineConfig } from 'vite'
102import { tanstackStart } from '@tanstack/react-start/plugin/vite'
103​
104export default defineConfig({
105 plugins: [
106 tanstackStart({
107 importProtection: {
108 // Always error, even in dev
109 behavior: 'error',
110 },
111 }),
112 ],
113})
114```
115​
116# Rsbuild
117​
118```ts title="rsbuild.config.ts"
119import { defineConfig } from '@rsbuild/core'
120import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
121​
122export default defineConfig({
123 plugins: [
124 tanstackStart({
125 importProtection: {
126 // Always error, even in dev
127 behavior: 'error',
128 },
129 }),
130 ],
131})
132```
133​
134<!-- ::end:tabs -->
135​
136Or set different behaviors per mode:
137​
138```ts
139importProtection: {
140 behavior: {
141 dev: 'mock',
142 build: 'error',
143 },
145```
146​
147## Configuring Deny Rules
148​
149You can add your own deny rules on top of the defaults. Rules are specified per environment using glob patterns (via [picomatch](https://github.com/micromatch/picomatch)) or regular expressions.
150​
151<!-- ::start:tabs variant="bundler" -->
152​
153# Vite
154​
155```ts title="vite.config.ts"
156import { defineConfig } from 'vite'
157import { tanstackStart } from '@tanstack/react-start/plugin/vite'
158​
159export default defineConfig({
160 plugins: [
161 tanstackStart({
162 importProtection: {
163 client: {
164 // Block specific npm packages from the client bundle
165 specifiers: ['@prisma/client', 'bcrypt'],
166 // Block files in a custom directory
167 files: ['**/db/**'],
168 },
169 server: {
170 // Block browser-only libraries from the server
171 specifiers: ['localforage'],
172 },
173 },
174 }),
175 ],
176})
177```
178​
179# Rsbuild
180​
181```ts title="rsbuild.config.ts"
182import { defineConfig } from '@rsbuild/core'
183import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
184​
185export default defineConfig({
186 plugins: [
187 tanstackStart({
188 importProtection: {
189 client: {
190 // Block specific npm packages from the client bundle
191 specifiers: ['@prisma/client', 'bcrypt'],
192 // Block files in a custom directory
193 files: ['**/db/**'],
194 },
195 server: {
196 // Block browser-only libraries from the server
197 specifiers: ['localforage'],
198 },
199 },
200 }),
201 ],
202})
203```
204​
205<!-- ::end:tabs -->
206​
207### Checking third-party packages
208​
209By default, resolved files inside `node_modules` are excluded from resolved-target deny checks (file-pattern and marker checks). This avoids false positives from packages that happen to use `.client.` or `.server.` in their distribution filenames. If you want to re-enable checking for a specific environment, set `excludeFiles` to an empty array:
210​
211```ts
212importProtection: {
213 server: {
214 // Re-enable file-pattern checking for node_modules in the server environment
215 excludeFiles: [],
216 },
218```
219​
220When you provide `excludeFiles`, it **fully replaces** the default (`['**/node_modules/**']`). To exclude additional paths while still skipping `node_modules`, include both:
221​
222```ts
223importProtection: {
224 client: {
225 excludeFiles: ['**/node_modules/**', '**/vendor/**'],
226 },
228```
229​
230## Scoping and Exclusions
231​
232By default, import protection only checks files inside Start's `srcDirectory`. You can change the scope with `include`, `exclude`, and `ignoreImporters`:
233​
234```ts
235importProtection: {
236 // Only check files matching these patterns
237 include: ['src/**'],
238 // Skip checking these files
239 exclude: ['src/generated/**'],
240 // Ignore violations when these files are the importer
241 ignoreImporters: ['**/*.test.ts', '**/*.spec.ts'],
243```
244​
245## Reading Violation Traces
246​
247When a violation is detected, the plugin shows a diagnostic message with the full import chain that led to the violation, a code snippet highlighting the offending line, and actionable suggestions.
248​
249### Server-only code in the client
250​
251This example shows a `*.server.*` file being imported transitively in the client environment:
252​
253```text
254[import-protection] Import denied in client environment
255​
256 Denied by file pattern: **/*.server.*
257 Importer: src/features/auth/session.ts:5:27
258 Import: "../db/queries.server"
259 Resolved: src/db/queries.server.ts
260​
261 Trace:
262 1. src/routes/index.tsx:2:34 (entry) (import "../features/auth/session")
263 2. src/features/auth/session.ts:5:27 (import "../db/queries.server")
264​
265 Code:
266 3 | import { logger } from '../utils/logger'
267 4 |
268 > 5 | import { getUsers } from '../db/queries.server'
269 | ^
270 6 |
271 7 | export function loadAuth() {
272​
273 src/features/auth/session.ts:5:27
274​
275 Suggestions:
276 - Wrap in createServerFn().handler(() => ...) to make it callable from the client via RPC
277 - Wrap in createServerOnlyFn(() => ...) if it should not be callable from the client
278 - Use createIsomorphicFn().client(() => ...).server(() => ...) for environment-specific implementations
279 - Split the file so client-safe exports are separate
280```
281​
282### Client-only code on the server
283​
284This example shows a `*.client.*` file imported in the SSR environment. Because the code snippet contains JSX, the `<ClientOnly>` suggestion is shown first:
285​
286```text
287[import-protection] Import denied in server environment
288​
289 Denied by file pattern: **/*.client.*
290 Importer: src/components/dashboard.tsx:3:30
291 Import: "./browser-widget.client"
292 Resolved: src/components/browser-widget.client.tsx
293​
294 Trace:
295 1. src/routes/dashboard.tsx:1:32 (entry) (import "../components/dashboard")
296 2. src/components/dashboard.tsx:3:30 (import "./browser-widget.client")
297​
298 Code:
299 1 | import { BrowserWidget } from './browser-widget.client'
300 2 |
301 > 3 | export function Dashboard() { return <BrowserWidget /> }
302 | ^
303 4 |
304​
305 src/components/dashboard.tsx:3:30
306​
307 Suggestions:
308 - Wrap in <ClientOnly fallback={...}>...</ClientOnly> to render only after hydration
309 - Wrap in createClientOnlyFn(() => ...) if it should only run in the browser
310 - Use createIsomorphicFn().client(() => ...).server(() => ...) for environment-specific implementations
311 - Split the file so server-safe exports are separate
312```
313​
314### How to read the output
315​
316Each violation message has these sections:
317​
318| Section | Description |
319| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
320| **Header** | Environment type where the violation occurred (`"client"` or `"server"`) |
321| **Denied by** | The rule that matched: file pattern, specifier pattern, or marker |
322| **Importer / Import / Resolved** | The importing file (with `file:line:col`), the raw import string, and the resolved target path |
323| **Trace** | The full import chain from the entry point to the denied import. Each step shows `file:line:col` and the import specifier used. Step 1 is always the entry point |
324| **Code** | A source code snippet with a `>` marker on the offending line and a `^` caret pointing to the exact column |
325| **Suggestions** | Actionable steps to fix the violation, tailored to the direction (server-in-client vs client-in-server) |
326​
327The trace reads top-to-bottom, from the entry point to the denied module. This helps you find where the chain starts so you can restructure your code.
328​
329## Common Pitfall: Why Some Imports Stay Alive
330​
331It can look like Start "should have removed that server-only import". The important detail is that this is handled by the Start compiler:
332​
3331. The compiler rewrites environment-specific _implementations_ for the current target (client or server).
3342. As part of that compilation, it prunes code and removes imports that become unused after the rewrite.
335​
336In practice, when the compiler replaces a `createServerFn()` handler with a client RPC stub, it can also remove server-only imports that were only used by the removed implementation.
337​
338Example (client build):
339​
340```ts
341import { getUsers } from './db/queries.server'
342import { createServerFn } from '@tanstack/react-start'
343​
344export const fetchUsers = createServerFn().handler(async () => {
345 return getUsers()
346})
347```
348​
349Conceptually, the client build output becomes something like (simplified):
350​
351```ts
352import { createClientRpc } from '@tanstack/react-start/client-rpc'
353import { createServerFn } from '@tanstack/react-start'
354​
355// Compiler replaces the handler with a client RPC stub.
356// (The id is generated by the compiler; treat it as an opaque identifier.)
357export const fetchUsers = TanStackStart.createServerFn({
358 method: 'GET',
359}).handler(createClientRpc('sha256:deadbeef...'))
360​
361// The server-only import is removed by the compiler.
362```
363​
364If the import "leaks" into code that survives compilation, it stays live and import protection will still flag it:
365​
366```ts
367import { getUsers } from './db/queries.server'
368import { createServerFn } from '@tanstack/react-start'
369​
370// This is fine -- the server implementation is removed for the client build
371export const fetchUsers = createServerFn().handler(async () => {
372 return getUsers()
373})
374​
375// This keeps the import alive in the client build
376export function leakyHelper() {
377 return getUsers() // referenced outside server boundary
379```
380​
381When this happens, you have a few options depending on what you want `leakyHelper` to be:
382​
383Option A: split the file so client code cannot accidentally import the leak
384​
385```ts
386// src/users.server.ts
387import { getUsers } from './db/queries.server'
388import { createServerFn } from '@tanstack/react-start'
389​
390// Safe to import from client code (compiler rewrites the handler)
391export const fetchUsers = createServerFn().handler(async () => {
392 return getUsers()
393})
394```
395​
396```ts
397// src/users-leaky.server.ts
398import { getUsers } from './db/queries.server'
399​
400// Server-only helper; do not import this from client code
401export function leakyHelper() {
402 return getUsers()
404```
405​
406Option B: keep it in the same file, but wrap the helper in `createServerOnlyFn`
407​
408This is useful when the helper should exist, but must never run on the client. Make sure the server-only import is only referenced inside the `createServerOnlyFn(() => ...)` callback:
409​
410```ts
411import { createServerOnlyFn } from '@tanstack/react-start'
412import { getUsers } from './db/queries.server'
413​
414export const leakyHelper = createServerOnlyFn(() => {
415 return getUsers()
416})
417```
418​
419On the client, the compiler output is effectively:
420​
421```ts
422export const leakyHelper = () => {
423 throw new Error(
424 'createServerOnlyFn() functions can only be called on the server!',
425 )
427```
428​
429Notice that the `createServerOnlyFn` import is gone, and the server-only `getUsers` import is also gone because it is no longer referenced after compilation.
430​
431The same idea applies to `createIsomorphicFn()`: the compiler removes the non-target implementation and prunes anything that becomes unused.
432​
433If you see an import-protection violation for a file you expected to be "compiled away", check whether the import is referenced outside a compiler-recognized environment boundary (or is otherwise kept live by surviving code).
434​
435## False Positives: Dev vs Build
436​
437In **build mode**, import protection defers violation checks until after tree-shaking. If an import is eliminated from the final bundle, no violation is reported. Build-time violations are definitive: if the build flags it, the import truly survived.
438​
439In **dev mode**, tree-shaking may be incomplete or unavailable, so import protection can report false positives for imports that would later be compiled away.
440​
441If a warning appears in dev but not build, that usually means the unsafe edge existed before tree-shaking but did not survive the final bundle. Even so, prefer changing the import structure so that edge does not exist in the first place.
442​
443## Mixed Barrels and Split Entry Points
444​
445Barrels are not inherently a false positive. The risky pattern is a barrel that mixes safe exports with environment-restricted ones from the same entry point.
446​
447Depending on what survives after compilation and tree-shaking, that can show up as either a real violation or a dev-only false positive. The safer structure is to split safe and restricted exports into separate entry points.
448​
449For example, avoid mixed barrels like this:
450​
451```ts
452// src/lib/index.ts
453export { fetchUsers } from './fetchUsers'
454export { getDb } from './db.server'
455```
456​
457```ts
458// src/routes/users.tsx
459import { fetchUsers } from '../lib'
460```
461​
462Even if the client only uses `fetchUsers`, that import path still goes through a module that re-exports `getDb`.
463​
464Prefer splitting safe and server-only exports into separate entry points:
465​
466```ts
467// src/lib/index.ts
468export { fetchUsers } from './fetchUsers'
469```
470​
471```ts
472// src/lib/server.ts
473export { getDb } from './db.server'
474```
475​
476```ts
477// src/routes/users.tsx
478import { fetchUsers } from '../lib'
479```
480​
481```ts
482// src/server/worker.ts
483import { getDb } from '../lib/server'
484```
485​
486The same applies to marker-protected files (`import '@tanstack/react-start/server-only'`). If a marked file is re-exported through a mixed barrel but never consumed by client code, production may suppress the warning after tree-shaking, but the better fix is still to avoid exposing that server-only edge to client-reachable code at all.
487​
488## The `onViolation` Callback
489​
490You can hook into violations for custom reporting or to override the verdict:
491​
492```ts
493importProtection: {
494 onViolation: async (info) => {
495 // info.env -- environment name (e.g. 'client', 'ssr', ...)
496 // info.envType -- 'client' or 'server'
497 // info.type -- 'specifier', 'file', or 'marker'
498 // info.specifier -- the raw import string
499 // info.importer -- absolute path of the importing file
500 // info.resolved -- absolute path of the resolved target (if available)
501 // info.trace -- array of { file, line?, column?, specifier? } objects
502 // info.snippet -- { lines, highlightLine, location } with the source code snippet (if available)
503​
504 // Return false (or Promise<false>) to allow this specific import (override the denial)
505 if (info.specifier === 'some-special-case') {
506 return false
507 }
508 },
510```
511​
512## Disabling Import Protection
513​
514To disable import protection entirely:
515​
516```ts
517importProtection: {
518 enabled: false,
520```
521​
522## Full Configuration Reference
523​
524```ts
525interface ImportProtectionOptions {
526 enabled?: boolean
527 behavior?:
528 | 'error'
529 | 'mock'
530 | { dev?: 'error' | 'mock'; build?: 'error' | 'mock' }
531 log?: 'once' | 'always'
532 include?: Array<string | RegExp>
533 exclude?: Array<string | RegExp>
534 ignoreImporters?: Array<string | RegExp>
535 maxTraceDepth?: number
536 client?: {
537 specifiers?: Array<string | RegExp>
538 files?: Array<string | RegExp>
539 excludeFiles?: Array<string | RegExp>
540 }
541 server?: {
542 specifiers?: Array<string | RegExp>
543 files?: Array<string | RegExp>
544 excludeFiles?: Array<string | RegExp>
545 }
546 onViolation?: (
547 info: ViolationInfo,
548 ) => boolean | void | Promise<boolean | void>
550```
551​
552| Option | Type | Default | Description |
553| --------------------- | -------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
554| `enabled` | `boolean` | `true` | Set to `false` to disable the plugin |
555| `behavior` | `string \| object` | `{ dev: 'mock', build: 'error' }` | What to do on violation |
556| `log` | `'once' \| 'always'` | `'once'` | Whether to deduplicate repeated violations |
557| `include` | `Pattern[]` | Start's `srcDirectory` | Only check importers matching these patterns |
558| `exclude` | `Pattern[]` | `[]` | Skip importers matching these patterns |
559| `ignoreImporters` | `Pattern[]` | `[]` | Ignore violations from these importers |
560| `maxTraceDepth` | `number` | `20` | Maximum depth for import traces |
561| `client` | `object` | See defaults above | Additional deny rules for the client environment |
562| `client.specifiers` | `Pattern[]` | Framework server specifiers | Specifier patterns denied in the client environment (additive with defaults) |
563| `client.files` | `Pattern[]` | `['**/*.server.*']` | File patterns denied in the client environment (replaces defaults) |
564| `client.excludeFiles` | `Pattern[]` | `['**/node_modules/**']` | Resolved files matching these patterns skip resolved-target checks (file-pattern + marker) (replaces defaults) |
565| `server` | `object` | See defaults above | Additional deny rules for the server environment |
566| `server.specifiers` | `Pattern[]` | `[]` | Specifier patterns denied in the server environment (replaces defaults; defaults for `server.specifiers` are `[]`, so unlike `client.specifiers` this isn't additive) |
567| `server.files` | `Pattern[]` | `['**/*.client.*']` | File patterns denied in the server environment (replaces defaults) |
568| `server.excludeFiles` | `Pattern[]` | `['**/node_modules/**']` | Resolved files matching these patterns skip resolved-target checks (file-pattern + marker) (replaces defaults) |
569| `onViolation` | `function` | `undefined` | Callback invoked on every violation |