Open History to see the last commit
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))
78}
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 },
144}
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 },
217}
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 },
227}
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'],
242}
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
378}
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()
403}
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 )
426}
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 },
509}
510```
511β
512## Disabling Import Protection
513β
514To disable import protection entirely:
515β
516```ts
517importProtection: {
518 enabled: false,
519}
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>
549}
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 |