You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can use `server-only` import to prevent accidentally importing server-only code on client, which can expose sensitive server code to public static assets.
504
508
509
+
For example, with the following codes:
510
+
505
511
- server-utils.js
506
512
507
513
```tsx
@@ -525,17 +531,13 @@ import { getData } from './server-utils.js' // ❌ This will fail at build time
525
531
...
526
532
```
527
533
528
-
When attempting to import server-only modules in client code, the plugin will show an error:
534
+
the plugin will show an error:
529
535
530
536
```sh
531
-
✘ [ERROR] "server-only" cannot be imported from a Client Component module. It should only be used from a Server Component.
532
-
533
-
client.js:2:25:
534
-
2 │ import { getData } from'./server-utils.js'
535
-
╵ ~~~~~~~~~~~~~~~~~~~
537
+
[rsc:validate-imports] 'server-only' cannot be imported in client build (importer:'/.../client.js', ...)
536
538
```
537
539
538
-
Similarly, `client-only` import can ensure browser-specific code isn't accidentally imported in server environment:
540
+
Similarly, `client-only` import can ensure browser-specific code isn't accidentally imported in server environment. For example,
539
541
540
542
- client-utils.js
541
543
@@ -559,24 +561,16 @@ export function ServerComponent() {
559
561
}
560
562
```
561
563
562
-
This will similarly fail at build time:
564
+
the plugin will show an error:
563
565
564
566
```sh
565
-
✘ [ERROR] "client-only" cannot be imported from a Server Component module. It should only be used from a Client Component.
566
-
567
-
server.js:1:27:
568
-
1 │ import { trackEvent } from'./client-utils.js'
569
-
╵ ~~~~~~~~~~~~~~~~~~~
567
+
[rsc:virtual-client-package] 'client-only' cannot be imported in server build (importer:'/.../server.js', ...)
570
568
```
571
569
572
-
Note that while there are official npm packages [`server-only`](https://www.npmjs.com/package/server-only) and [`client-only`](https://www.npmjs.com/package/client-only) created by React team, they don't need to be installed. The plugin internally handles these imports and provides build-time validation instead of runtime errors.
570
+
Note that while there are official npm packages [`server-only`](https://www.npmjs.com/package/server-only) and [`client-only`](https://www.npmjs.com/package/client-only) created by React team, they don't need to be installed. The plugin internally overrides these imports and provides build-time validation instead of runtime errors.
573
571
574
572
This build-time validation is enabled by default and can be disabled by setting `validateImports:false` in the plugin options.
0 commit comments