Skip to content

Commit 7c58156

Browse files
fix: import protection robustness
1 parent c137bbc commit 7c58156

15 files changed

Lines changed: 664 additions & 14 deletions

File tree

‎docs/start/framework/react/guide/import-protection.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,14 @@ The same idea applies to `createIsomorphicFn()`: the compiler removes the non-ta
335335

336336
If 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).
337337

338+
## False Positives: Dev vs Build
339+
340+
In **build mode**, the plugin defers violation checks until after tree-shaking. If an import is eliminated from the final bundle (e.g., a barrel re-exports a `.server` module but no client code actually uses that export), no violation is reported. This means build-time violations are definitive — if the build flags it, the import truly survived.
341+
342+
In **dev mode**, there is no tree-shaking. The plugin uses graph reachability to filter violations, but it cannot determine whether individual bindings are unused. This means barrel re-exports of `.server` or marker-protected modules may produce warnings even when the server-only exports would be tree-shaken away in production. These dev warnings are informational — run a build to confirm whether the violation is real.
343+
344+
The same applies to marker-protected files (`import '@tanstack/react-start/server-only'`). If a marked file is re-exported through a barrel but never consumed by client code, the build correctly suppresses the violation while dev may still warn.
345+
338346
## The `onViolation` Callback
339347

340348
You can hook into violations for custom reporting or to override the verdict:

‎e2e/react-start/import-protection/src/routes/__root.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ function RootComponent() {
3434
<Link to="/client-only-jsx">Client-Only JSX</Link>
3535
{' | '}
3636
<Link to="/beforeload-leak">Beforeload Leak</Link>
37+
{' | '}
38+
<Link to="/component-server-leak">Component Server Leak</Link>
39+
{' | '}
40+
<Link to="/barrel-false-positive">Barrel False Positive</Link>
3741
</nav>
3842
<Outlet />
3943
<Scripts />
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { createFileRoute } from '@tanstack/react-router'
2+
import { createServerFn } from '@tanstack/react-start'
3+
// Import from the barrel — NOT directly from .server.
4+
// `getUsers` (from ./db.server) is only used inside a server fn (compiler strips it).
5+
// `userColumns` (from ./shared) is a plain object used in JSX — not server-only.
6+
// Tree-shaking should eliminate the ./db.server dependency entirely from the
7+
// client bundle, so no import-protection violation should fire for it.
8+
import { getUsers, userColumns, type User } from '../violations/barrel-reexport'
9+
10+
const fetchUsers = createServerFn().handler(async () => {
11+
return getUsers()
12+
})
13+
14+
export const Route = createFileRoute('/barrel-false-positive')({
15+
loader: () => fetchUsers(),
16+
component: BarrelFalsePositive,
17+
})
18+
19+
function BarrelFalsePositive() {
20+
const users = Route.useLoaderData()
21+
22+
return (
23+
<div>
24+
<h1 data-testid="barrel-heading">Barrel False Positive</h1>
25+
<table>
26+
<thead>
27+
<tr>
28+
<th data-testid="col-name">{userColumns.name}</th>
29+
<th data-testid="col-email">{userColumns.email}</th>
30+
</tr>
31+
</thead>
32+
<tbody>
33+
{users.map((user: User) => (
34+
<tr key={user.id}>
35+
<td>{user.name}</td>
36+
<td>{user.email}</td>
37+
</tr>
38+
))}
39+
</tbody>
40+
</table>
41+
</div>
42+
)
43+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { createFileRoute } from '@tanstack/react-router'
2+
// This import is used ONLY inside the route component.
3+
// The router plugin code-splits the component into a lazy chunk,
4+
// moving this import into the split module.
5+
// Import protection must still catch this as a violation.
6+
import { getComponentSecret } from '../violations/db-credentials.server'
7+
8+
export const Route = createFileRoute('/component-server-leak')({
9+
component: ComponentServerLeak,
10+
})
11+
12+
function ComponentServerLeak() {
13+
return (
14+
<div>
15+
<h1 data-testid="component-leak-heading">Component Server Leak</h1>
16+
<p data-testid="component-leak-secret">{getComponentSecret()}</p>
17+
</div>
18+
)
19+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Server-only database module.
3+
* Only exports server-only values: getUsers (DB access) and User type.
4+
* The side-effect (DATABASE_URL log) should NOT reach the client.
5+
*/
6+
7+
const DATABASE_URL =
8+
process.env.DATABASE_URL ?? 'postgres://admin:s3cret@localhost:5432/myapp'
9+
10+
console.log(`[db] connecting to ${DATABASE_URL}`)
11+
12+
export interface User {
13+
id: number
14+
name: string
15+
email: string
16+
}
17+
18+
const FAKE_USERS: Array<User> = [
19+
{ id: 1, name: 'Alice', email: '[email protected]' },
20+
{ id: 2, name: 'Bob', email: '[email protected]' },
21+
]
22+
23+
export async function getUsers(): Promise<Array<User>> {
24+
await new Promise((r) => setTimeout(r, 50))
25+
return FAKE_USERS
26+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Server-only module protected by the marker import pattern.
3+
* Re-exported through the barrel (index.ts) but never imported by
4+
* barrel-false-positive.tsx — tree-shaking eliminates it from the
5+
* client bundle, so no import-protection violation should fire.
6+
*/
7+
import '@tanstack/react-start/server-only'
8+
9+
export function foo(): string {
10+
return 'server-only value from foo'
11+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Barrel file — NOT a .server file itself.
3+
* Re-exports from a .server module, a marker-protected module, and a shared module.
4+
*
5+
* The key scenario: a consumer imports { getUsers, userColumns } from here.
6+
* - getUsers comes from ./db.server (server-only via file suffix)
7+
* - foo comes from ./foo (server-only via marker import)
8+
* - userColumns comes from ./shared (client-safe)
9+
*
10+
* If getUsers is only used inside a createServerFn handler (compiler strips it),
11+
* and foo is never imported by the consumer at all, tree-shaking should eliminate
12+
* both ./db.server and ./foo from the client bundle — so the import-protection
13+
* plugin should NOT fire violations for either.
14+
*/
15+
export { getUsers, type User } from './db.server'
16+
export { foo } from './foo'
17+
export { userColumns } from './shared'
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Shared (non-server) module with client-safe values.
3+
* These are safe to use on the client.
4+
*/
5+
import type { User } from './db.server'
6+
7+
export const userColumns = {
8+
name: 'Full Name',
9+
email: 'Email Address',
10+
} as const
11+
12+
/** Placeholder for when no users have loaded yet. */
13+
export const emptyUser: User = { id: 0, name: '', email: '' }
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Server-only secret used exclusively inside a route component.
3+
* The route component is code-split by the router plugin into a separate
4+
* lazy chunk, so the import to this file ends up in the split module —
5+
* NOT the original route file. Import protection must still detect this.
6+
*/
7+
export const COMPONENT_SECRET = 'component-only-server-secret-99999'
8+
9+
export function getComponentSecret() {
10+
return COMPONENT_SECRET
11+
}

‎e2e/react-start/import-protection/tests/error-mode.setup.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ const routes = [
104104
'/client-only-violations',
105105
'/client-only-jsx',
106106
'/beforeload-leak',
107+
'/barrel-false-positive',
107108
]
108109

109110
async function captureDev(cwd: string): Promise<void> {

0 commit comments

Comments
 (0)