Skip to content

Commit 7eee041

Browse files
committed
wip
1 parent d46b0df commit 7eee041

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

packages/plugin-rsc/README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,72 @@ import.meta.viteRsc.loadModule
498498
499499
See also [Vite documentation](https://vite.dev/guide/api-hmr.html#intellisense-for-typescript) for `vite/client` types.
500500
501+
## `server-only` and `client-only` import
502+
503+
You can use `server-only` import to avoid accidentally leaking certain modules on client build, which becomes public static assets.
504+
505+
For example, ...todo
506+
507+
- server-utils.js
508+
509+
```tsx
510+
import 'server-only'
511+
512+
export async function getData() {
513+
const res = await fetch('https://service-internal-service.com/data', {
514+
headers: {
515+
authorization: process.env.API_KEY,
516+
},
517+
})
518+
return res.json()
519+
}
520+
```
521+
522+
- client.js
523+
524+
```tsx
525+
'use client'
526+
import { getData } from './api-utils.js'
527+
528+
export function ClientComponent() {
529+
const data = await getData()
530+
return <div>{data.message}</div>
531+
}
532+
```
533+
534+
The plugin will show a following error ....todo
535+
536+
```sh
537+
`server-only` cannot be imported in client build
538+
```
539+
540+
On the other way around, `client-only` import ...todo
541+
542+
- server.js
543+
544+
```tsx
545+
export function ServerComponent() {
546+
todo
547+
}
548+
```
549+
550+
- client-utils.js
551+
552+
```tsx
553+
import 'client-only'
554+
555+
todo
556+
```
557+
558+
Note that 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,
559+
but they don't need to be installed. `@vitejs/plugin-rsc` internally overrides them to provide a better error message during time instead of runtime error provided by the actual packages.
560+
561+
This build time valdiation is enabled by default and it can be disabled by `RscPluginOptions.validateImports: false`.
562+
563+
<!-- Learn more in -->
564+
<!-- https://nextjs.org/docs/app/getting-started/server-and-client-components#preventing-environment-poisoning -->
565+
<!-- https://overreacted.io/how-imports-work-in-rsc/ -->
566+
501567
## Credits
502568
503569
This project builds on fundamental techniques and insights from pioneering Vite RSC implementations.

0 commit comments

Comments
 (0)