@vitejs/plugin-rsc
This package provides React Server Components (RSC) support for Vite.
Features
- Framework-agnostic: The plugin implements RSC bundler features and provides low level RSC runtime (
react-server-dom) API without framework-specific abstractions.
- Runtime-agnostic: Built on Vite environment API and works with other runtimes (e.g.,
@cloudflare/vite-plugin).
- HMR support: Enables editing both client and server components without full page reloads.
- CSS support: CSS is automatically code-split both at client and server components and they are injected upon rendering.
Getting Started
You can create a starter project by:
npm create vite@latest -- --template rsc
Examples
Start here: ./examples/starter - Recommended for understanding the package
- Provides an in-depth overview of API with inline comments to explain how they function within RSC-powered React application.
Integration examples:
./examples/basic - Comprehensive showcase of standard RSC features and the primary E2E test fixture.
./examples/use-cache - Local cached functions and components demonstrating argument keys, Flight replay, dynamic children, captured values, and invalidation.
./examples/use-cache-callable - Cached server references demonstrating inline and file directives, client invocation, argument admission, and encrypted closure captures.
./examples/use-cache-persistent - Persistent callable cache entries demonstrating Flight value replay and dependency-aware development invalidation.
./examples/custom-server-function - Third-party Server Function directive integration using server reference claims.
./examples/ssg - Static site generation with MDX and client components for interactivity.
./examples/ppr - Partial prerendering with a reusable static HTML shell and request-time RSC content.
./examples/no-ssr - RSC application without an SSR environment.
./examples/node-stream - Starter application served end to end through Node.js request, response, and stream APIs.
./examples/client-first - Experimental client-owned page that consumes RSC function results.
./examples/action-reachability - Route-aware dispatch for a retained server action.
./examples/browser-mode - Advanced setup that runs both RSC and React client environments in the browser with custom module loading.
./examples/performance-track - Minimal React Server Components performance track probe.
./examples/react-router - React Router RSC integration
Basic Concepts
This example is a simplified version of ./examples/starter. You can read ./examples/starter/src/framework/entry.{rsc,ssr,browser}.tsx for more in-depth commentary, which includes server function handling and client-side RSC re-fetching/re-rendering.
This is the diagram to show the basic flow of RSC rendering process. See also https://github.com/hi-ogawa/vite-plugins/discussions/606.
graph TD
subgraph "<strong>rsc environment</strong>"
A["React virtual dom tree"] --> |"[@vitejs/plugin-rsc/rsc/server]<br /><code>renderToReadableStream</code>"| B1["RSC Stream"];
end
B1 --> B2
B1 --> B3
subgraph "<strong>ssr environment</strong>"
B2["RSC Stream"] --> |"[@vitejs/plugin-rsc/ssr]<br /><code>createFromReadableStream</code>"| C1["React virtual dom tree"];
C1 --> |"[react-dom/server]<br/>SSR"| E["HTML String/Stream"];
end
subgraph "<strong>client environment</strong>"
B3["RSC Stream"] --> |"[@vitejs/plugin-rsc/browser]<br /><code>createFromReadableStream</code>"| C2["React virtual dom tree"];
C2 --> |"[react-dom/client]<br/>CSR: mount, hydration"| D["DOM Elements"];
end
style A fill:#D6EAF8,stroke:#333,stroke-width:2px
style B1 fill:#FEF9E7,stroke:#333,stroke-width:2px
style B2 fill:#FEF9E7,stroke:#333,stroke-width:2px
style B3 fill:#FEF9E7,stroke:#333,stroke-width:2px
style C1 fill:#D6EAF8,stroke:#333,stroke-width:2px
style C2 fill:#D6EAF8,stroke:#333,stroke-width:2px
style D fill:#D5F5E3,stroke:#333,stroke-width:2px
style E fill:#FADBD8,stroke:#333,stroke-width:2px
import rsc from '@vitejs/plugin-rsc'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
// add plugin
rsc(),
],
// specify entry point for each environment.
environments: {
// `rsc` environment loads modules with `react-server` condition.
// this environment is responsible for:
// - RSC stream serialization (React VDOM -> RSC stream)
// - server functions handling
rsc: {
build: {
rollupOptions: {
input: {
index: './src/framework/entry.rsc.tsx',
},
},
},
},
// `ssr` environment loads modules without `react-server` condition.
// this environment is responsible for:
// - RSC stream deserialization (RSC stream -> React VDOM)
// - traditional SSR (React VDOM -> HTML string/stream)
ssr: {
build: {
rollupOptions: {
input: {
index: './src/framework/entry.ssr.tsx',
},
},
},
},
// client environment is used for hydration and client-side rendering
// this environment is responsible for:
// - RSC stream deserialization (RSC stream -> React VDOM)
// - traditional CSR (React VDOM -> Browser DOM tree mount/hydration)
// - refetch and re-render RSC
// - calling server functions
client: {
build: {
rollupOptions: {
input: {
index: './src/framework/entry.browser.tsx',
},
},
},
},
},
})
import { renderToReadableStream } from '@vitejs/plugin-rsc/rsc/server'
// the plugin assumes `rsc` entry having default export of request handler
export default async function handler(request: Request): Promise<Response> {
// serialize React VDOM to RSC stream
const root = (
<html>
<body>
<h1>Test</h1>
</body>
</html>
)
const rscStream = renderToReadableStream(root)
// respond direct RSC stream request based on framework's convention
if (request.url.endsWith('.rsc')) {
return new Response(rscStream, {
headers: {
'Content-type': 'text/x-component;charset=utf-8',
},
})
}
// delegate to SSR environment for html rendering
// `loadModule` is a helper API provided by the plugin for multi environment interaction.
const ssrEntry = await import.meta.viteRsc.loadModule<
typeof import('./entry.ssr.tsx')
>('ssr', 'index')
const htmlStream = await ssrEntry.handleSsr(rscStream)
// respond html
return new Response(htmlStream, {
headers: {
'Content-type': 'text/html',
},
})
}
// add `import.meta.hot.accept` to handle server module change efficiently
if (import.meta.hot) {
import.meta.hot.accept()
}
import {
createFromReadableStream,
getClientEntryUrl,
} from '@vitejs/plugin-rsc/ssr'
import { renderToReadableStream } from 'react-dom/server.edge'
export async function handleSsr(rscStream: ReadableStream) {
// deserialize RSC stream back to React VDOM
const root = await createFromReadableStream(rscStream)
// render html (traditional SSR)
const htmlStream = renderToReadableStream(root, {
bootstrapModules: [getClientEntryUrl()],
})
return htmlStream
}
import { createFromReadableStream } from '@vitejs/plugin-rsc/browser'
import { hydrateRoot } from 'react-dom/client'
async function main() {
// fetch and deserialize RSC stream back to React VDOM
const rscResponse = await fetch(window.location.href + '.rsc')
const root = await createFromReadableStream(rscResponse.body)
// hydration (traditional CSR)
hydrateRoot(document, root)
}
main()
Environment helper API
The plugin provides an additional helper for multi environment interaction.
Available on rsc or ssr environment
import.meta.viteRsc.loadModule
- Type:
(environmentName: "ssr" | "rsc", entryName?: string) => Promise<T>
This allows importing ssr environment module specified by environments.ssr.build.rollupOptions.input[entryName] inside rsc environment and vice versa. When entryName is omitted, the function automatically uses the single entry from the target environment's rollupOptions.input.
During development, by default, this API assumes both rsc and ssr environments execute under the main Vite process as RunnableDevEnvironment. Internally, loadModule uses the global __VITE_ENVIRONMENT_RUNNER_IMPORT__ function to import modules in the target environment (see __VITE_ENVIRONMENT_RUNNER_IMPORT__ below).
When enabling rsc({ loadModuleDevProxy: true }) plugin option, the loaded module is implemented as a proxy with fetch-based RPC to call in node environment on the main Vite process, which for example, allows rsc environment inside cloudflare workers to access ssr environment on the main Vite process. This proxy mechanism uses turbo-stream for serializing data types beyond JSON, with custom encoders/decoders to additionally support Request and Response instances.
During production build, this API will be rewritten into a static import of the specified entry of other environment build and the modules are executed inside the same runtime.
For example,
// ./entry.rsc.tsx
const ssrModule = await import.meta.viteRsc.loadModule("ssr", "index");
ssrModule.renderHTML(...);
// ./entry.ssr.tsx (with environments.ssr.build.rollupOptions.input.index = "./entry.ssr.tsx")
export function renderHTML(...) {}
import.meta.viteRsc.import
- Type:
<T>(specifier: string, options: { environment: string }) => Promise<T>
A more ergonomic alternative to loadModule:
- No manual
rollupOptions.input config needed - entries are auto-discovered
- Specifier matches the path in
typeof import(...) type annotations
Comparison:
// Before (loadModule) - requires vite.config.ts:
// environments.ssr.build.rollupOptions.input = { index: './entry.ssr.tsx' }
import.meta.viteRsc.loadModule<typeof import('./entry.ssr.tsx')>('ssr', 'index')
// After (import) - no config needed, auto-discovered
import.meta.viteRsc.import<typeof import('./entry.ssr.tsx')>(
'./entry.ssr.tsx',
{ environment: 'ssr' },
)
During development, this works the same as loadModule, using the __VITE_ENVIRONMENT_RUNNER_IMPORT__ function to import modules in the target environment.
During production build, the plugin auto-discovers these imports and emits them as entries in the target environment. A manifest file (__vite_rsc_env_imports_manifest.js) is generated to map module specifiers to their output filenames.
Available on rsc environment
import.meta.viteRsc.loadCss
[!NOTE]
The plugin automatically injects CSS for server components. See the CSS Support section for detailed information about automatic CSS injection.
- Type:
(importer?: string) => React.ReactNode
This allows collecting css which is imported through a current server module and injecting them inside server components.
import './test.css'
import dep from './dep.tsx'
export function ServerPage() {
// this will include css assets for "test.css"
// and any css transitively imported through "dep.tsx"
return (
<>
{import.meta.viteRsc.loadCss()}
...
</>
)
}
When specifying loadCss(<id>), it will collect css through the server module resolved by <id>.
// virtual:my-framework-helper
export function Assets() {
return <>
{import.meta.viteRsc.loadCss("/routes/home.tsx")}
{import.meta.viteRsc.loadCss("/routes/about.tsx")}
{...}
</>
}
// user-app.tsx
import { Assets } from "virtual:my-framework-helper";
export function UserApp() {
return <html>
<head>
<Assets />
</head>
<body>...</body>
</html>
}
Available on ssr environment
getClientEntryUrl()
This returns the URL used to load the client entry specified by environments.client.build.rollupOptions.input.index. This can be used with React DOM SSR APIs such as renderToReadableStream.
import { getClientEntryUrl } from '@vitejs/plugin-rsc/ssr'
import { renderToReadableStream } from 'react-dom/server.edge'
const htmlStream = await renderToReadableStream(reactNode, {
bootstrapModules: [getClientEntryUrl()],
})
getClientEntryUrl() cannot be used when the customClientEntry plugin option is enabled.
Available on client environment
rsc:update event
This event is fired when server modules are updated, which can be used to trigger re-fetching and re-rendering of RSC components on browser.
import { createFromFetch } from '@vitejs/plugin-rsc/browser'
import.meta.hot.on('rsc:update', async () => {
// re-fetch RSC stream
const rscPayload = await createFromFetch(fetch(window.location.href + '.rsc'))
// re-render ...
})
Global API
__VITE_ENVIRONMENT_RUNNER_IMPORT__
- Type:
(environmentName: string, id: string) => Promise<any>
This global function provides a standardized way to import a module in a given environment during development. It is used internally by import.meta.viteRsc.loadModule to execute modules in the target environment.
By default, the plugin sets this global to import via the environment's module runner:
globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (environmentName, id) => {
return server.environments[environmentName].runner.import(id)
}
Custom Environment Integration:
Frameworks with custom environment setups (e.g., environments running in separate workers or with custom module loading) can override this global to provide their own module import logic.
// Custom logic to import module between multiple environments inside worker
globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (environmentName, id) => {
return myWorkerRunners[environmentname].import(id)
}
This allows import.meta.viteRsc.loadModule to work seamlessly with different runtime configurations without requiring changes to user code.
Plugin API
@vitejs/plugin-rsc
- Type:
rsc: (options?: RscPluginOptions) => Plugin[];