React Server Components Without Next.js: Using RSC with Vite, Waku, and React Router 7
You don't need Next.js to use React Server Components anymore. Explore how the Vite Environment API, Waku, and React Router 7 let you run RSC on any Node, Bun, Cloudflare, or Docker server.

[!IMPORTANT]
Direct Answer (AIEO Summary): React Server Components are a React 19 architecture, not a Next.js-only feature. Thanks to Vite's Environment API (@vitejs/plugin-rsc), you can run production RSC apps today using Waku (a minimal, Vite-powered RSC framework), React Router 7 RSC Mode (ideal for upgrading existing Remix or SPA codebases), or a custom Vite + Express/Hono server—giving you zero vendor lock-in and portability to Docker, Cloudflare Workers, Bun, or Netlify.
Published as Part 7 of the 10-Part FutureStack React Server Components Deep-Dive Series. Every code example, architecture diagram, and interactive React widget below is written for production React 19 & modern full-stack engineering teams.
1. Why RSC Looked Locked to Next.js—And What Changed
For a long time, if you wanted to use React Server Components (RSC), you had exactly one choice: Next.js. This created a widespread belief that RSC was a Next.js feature rather than a React feature. If you were building a high-performance dashboard or a specialized internal tool and didn't want the overhead of a full-stack framework, you were stuck with traditional Client-Side Rendering (CSR) or standard Server-Side Rendering (SSR).
The reason for this "lock-in" wasn't a secret deal between Meta and Vercel. It was a massive engineering hurdle. To make RSC work, a bundler has to do things that standard tools like Webpack or early versions of Vite simply weren't designed to do. Specifically, the bundler has to manage three entirely different versions of your application simultaneously, ensuring they can all talk to each other without leaking secrets or bloating the browser bundle.
The Three-Graph Problem: Why RSC is Hard
In a traditional React SPA, your bundler (like Vite or Esbuild) creates a single "module graph." It starts at main.tsx, follows every import, and bundles it all for the browser. When we moved to SSR, we needed two graphs: one for the browser and one for the server to generate the initial HTML.
RSC changes the game by requiring three distinct module graphs that must be perfectly synchronized. If they fall out of sync, your app crashes with cryptic errors like Maximum call stack size exceeded or the dreaded Expected a Client Component, but got a Server Component.
- The RSC Server Graph: This contains your Server Components. It runs only on the server (Node.js, Bun, or Edge). It can access databases and file systems directly. Crucially, it must ignore any browser-only code.
- The SSR Graph: This is used to turn your components into a flat HTML string for the initial page load. It needs to know about both Server and Client components but only to generate their initial visual state.
- The Client Graph: This is what actually ships to the user's browser. It must contain zero Server Component code. If a single
pg(PostgreSQL) client or a secret API key leaks into this graph, you have a major security vulnerability.
Managing these three graphs requires a "module condition" system. When you import react, the bundler must decide: "Am I in a react-server environment or a standard browser environment?" Next.js solved this by heavily customizing Webpack. They spent years building the glue code that allows a Server Component to "reference" a Client Component without actually including the Client Component's source code in the server's memory.
[!NOTE] This "referencing" is handled via the React Server Components Explained: Inside the RSC Flight Wire Protocol. Instead of passing code, the server passes a "placeholder ID" that the browser uses to look up the actual JavaScript chunk.
How Vite's Environment API Broke the Monopoly
The landscape shifted with the release of the Vite Environment API (introduced in Vite 6). Before this, Vite essentially assumed there were only two environments: client and ssr. This made implementing RSC in Vite a nightmare of hacks and multiple compiler passes.
The new Environment API allows developers to define an unlimited number of custom runtimes within a single Vite instance. Frameworks like Waku Minimal React RSC Framework and the upcoming React Router 7 (formerly Remix) use this to create a dedicated rsc environment. This environment uses the react-server export condition, which tells libraries to provide their server-only versions.
When you run a modern RSC-capable bundler, it doesn't just "build" your app. It orchestrates a handoff. The rsc environment processes a component, encounters a "use client" directive, stops traversing that branch, and hands a "reference" over to the client environment. This separation is what allows us to finally use Official React Server Components Reference (react.dev) without being forced into the Next.js ecosystem.
| Feature | Traditional SSR | React Server Components (RSC) |
|---|---|---|
| Data Fetching | Happens in getServerSideProps or useEffect | Happens directly inside the Component function |
| Bundle Size | Includes all dependencies used for rendering | Only includes Client Component dependencies |
| Interactivity | Everything is hydrated | Only "Client Components" are hydrated |
| Server Secrets | Must be carefully managed in separate files | Safe to use directly in Server Components |
| Re-rendering | Re-renders the whole page or uses client state | Can refresh server data without losing client state |
The "Flight" Protocol: The Invisible Bridge
To understand why we can now move away from Next.js, we have to look at how the server talks to the browser. It doesn't send HTML for every update. It sends a specialized JSON-like stream called the "Flight" format.
If you've ever looked at the Network tab in a Next.js app and seen a request returning lines starting with 1:I{"id":"...","chunks":[]}, you've seen Flight. This protocol is what allows the browser to update the UI without a full page reload, while still keeping the logic on the server.
The challenge for non-Next.js tools was implementing the "Flight Server" and "Flight Client." React provides these as react-server-dom-webpack (yes, the name is confusingly Webpack-specific, but it works elsewhere) and react-server-dom-vite. These packages are the "engine" of RSC. What changed is that the community finally figured out how to wire these engines into Vite's dev server.
In a production environment, this improves the web.dev Time to First Byte (TTFB) Guide because the server can start streaming the UI to the browser before the entire data fetch is even finished.
// This is a Server Component.
// It runs ONLY on the server.
import { db } from '../lib/database';
export async function ProductList() {
// We can call the database directly.
// No need for an internal API route or useEffect.
const products = await db.query('SELECT * FROM products LIMIT 10');
return (
<div className="grid gap-4">
{products.map((product) => (
<div key={product.id} className="p-4 border rounded">
<h2 className="font-bold">{product.name}</h2>
<p>{product.price}</p>
{/*
This is a Client Component being used inside a Server Component.
The bundler replaces this with a reference ID in the Flight stream.
*/}
<AddToCartButton productId={product.id} />
</div>
))}
</div>
);
}Real-World Debugging: The "Module Not Found" Trap
When moving away from Next.js to a custom Vite-based RSC setup, you will inevitably hit the "Module Not Found" or "Invalid Hook Call" errors. These happen because of how the react-server condition works.
In a standard Node.js environment, import { useState } from 'react' works fine. But in a react-server environment, React intentionally exports a version of itself that throws an error if you try to use useState. This is a safety mechanism to prevent you from accidentally putting stateful logic on the server where it can't run.
If you are building your own RSC integration, your Vite config must look something like this to handle the environment split:
import { defineConfig } from 'vite';
import react from '@vitejs/react-swc';
export default defineConfig({
plugins: [react()],
// The magic happens here:
ssr: {
// We tell Vite which packages should be treated as
// part of the Server Component graph.
resolve: {
conditions: ['react-server', 'node'],
},
// Prevent leaking browser-only packages into the server
noExternal: ['@headlessui/react', 'lucide-react'],
},
builder: {
// Vite 6 Environment API allows us to define
// the 'rsc' environment explicitly.
environments: {
rsc: {
resolve: {
conditions: ['react-server'],
},
},
client: {
resolve: {
conditions: ['browser'],
},
},
},
},
});The complexity of this configuration is why it took so long for alternatives to emerge. You aren't just configuring a build tool; you are defining the physical boundaries of where your code is allowed to exist. If you get it wrong, you might accidentally expose a database password to the browser. For a deeper look at protecting your app, check out our guide on React Server Components Security: Preventing Data Leaks, IDOR, and Server Action Exploits.
Why "Vanilla" RSC Matters for the Ecosystem
Why go through all this trouble just to avoid Next.js? It's about flexibility and the "Unix Philosophy" of software. Next.js is an all-in-one opinionated framework. It dictates your routing, your caching strategy, and your deployment target (ideally Vercel).
By using RSC with Vite or Waku, you regain control over:
- The Router: You can use the new React Router 7 or even a simple state-based router if you're building a single-page widget.
- The Server: You can run your RSC server on a standard Express app, a Fastify instance, or even a Cloudflare Worker without needing a heavy framework adapter.
- The Build Pipeline: You can integrate with existing Vite plugins for Vitest, Tailwind, or specialized asset pipelines that might not play well with Next.js's internal Webpack/Turbopack setup.
This shift is similar to how we moved from massive jQuery UI libraries to modular React components. We are moving from "RSC as a Framework" to "RSC as a Primitive." In the following chapters, we will walk through the exact steps to build this setup from scratch, starting with the minimal primitives needed to get a Server Component rendering in a basic Vite project.
Interactive Engineering Lab: Try It Yourself
Experiment directly with the live interactive React asset below to see the architecture concepts from this guide update in real time—no external sandbox required.
2. Inside Vite's Environment API & @vitejs/plugin-rsc
Vite was originally built to bundle code for one place: the browser. When we talk about React Server Components (RSC), that single-target model breaks. To run RSC without Next.js, your build tool must manage three distinct versions of your code simultaneously. You need a version for the browser (Client), a version for the initial HTML generation (SSR), and a version for the data-fetching logic that never leaves the server (RSC).
Vite's Environment API is the infrastructure that makes this multi-target orchestration possible. It allows a single Vite dev server to run different "environments," each with its own module graph, transform pipeline, and resolve logic. If you are coming from a standard Vite setup, you are used to one index.html and one entry point. In an RSC setup, Vite acts more like a conductor of an orchestra, ensuring that a change in a Server Component triggers the right updates without breaking the Client Components that depend on them.
The Three-Headed Module Graph: Client, SSR, and RSC
In a traditional React app, Vite builds a single dependency graph. You import a component, and it gets bundled. With RSC, Vite must maintain three separate graphs that talk to each other. This is where most developers get confused. They assume RSC is just "SSR with more steps," but as I explain in React Server Components vs. SSR: Why They Solve Completely Different Problems, the execution models are fundamentally different.
The client environment handles your standard React components—the ones with useState and useEffect. The ssr environment takes those same components and runs them on the server just once to generate the initial HTML string. The rsc environment is the new player. It only runs on the server, it can talk directly to your database, and it outputs a special serialized stream (the "Flight" format) instead of HTML.
Vite manages these through the environments configuration key. Each environment can have its own resolve.conditions. For example, the RSC environment might look for a react-server condition in package.json to ensure it loads the server-only version of a library, while the client environment looks for browser.
| Feature | Client Environment | SSR Environment | RSC Environment |
|---|---|---|---|
| Output | JS Bundles / Assets | HTML String | RSC Payload (JSON-like) |
| Directives | Honors 'use client' | Honors 'use client' | Honors 'use server' |
| HMR Target | Browser Window | Server-side Cache | Server-side Cache |
| Global Access | window, document | global, process | global, process, DB |
Managing these three graphs manually would be a nightmare. This is why @vitejs/plugin-rsc (and the logic inside frameworks like Waku or React Router 7) is essential. It tells Vite how to jump between these graphs. When the RSC graph encounters a file with the 'use client' directive, the plugin doesn't bundle that code into the server build. Instead, it creates a "Client Reference"—a tiny pointer that says, "Stop here; this part belongs to the browser graph." You can find the technical details of this handoff in the React 'use client' Directive Specification (react.dev).
How @vitejs/plugin-rsc Orchestrates the Build
The @vitejs/plugin-rsc is the glue. Its primary job is to intercept imports and decide which environment should handle them. When you run vite dev, the plugin starts a worker thread or a separate execution context for the RSC environment.
The most critical task of the plugin is "Module Transformation." When the server-side code imports a component marked with 'use client', the plugin transforms that import into a serialized object. This object contains the file path and the export name. This is why you can't pass functions as props from a Server Component to a Client Component—you can't serialize a live function into a string pointer.
[!IMPORTANT]
A common production error occurs when a library doesn't explicitly mark itself with 'use client'. Vite will try to execute it in the RSC environment. If that library uses window or useLayoutEffect, your server will crash with a "ReferenceError: window is not defined." You must wrap these third-party components in your own 'use client' files to create a boundary.
Below is a conceptual look at how you configure Vite to handle these multiple environments. Note how we define the rsc and client targets separately within the same config.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { rscPlugin } from './plugins/rsc-logic'; // Conceptual custom plugin
export default defineConfig({
plugins: [
react(),
rscPlugin(),
],
// Vite 6+ Environment API configuration
environments: {
client: {
build: {
outDir: 'dist/client',
rollupOptions: { input: 'src/entry-client.tsx' },
},
},
rsc: {
resolve: {
// This tells Vite to prefer the server-specific versions of React
conditions: ['react-server', 'node', 'import'],
},
build: {
outDir: 'dist/rsc',
ssr: true, // RSC always runs in an SSR-like context
rollupOptions: { input: 'src/entry-rsc.tsx' },
},
},
},
});The plugin also handles the "Server Action" transformation. When it sees 'use server' at the top of a function, it strips the function body from the client bundle and replaces it with a fetch call to the server. This ensures your sensitive database logic or API keys never end up in the user's browser. If you're building complex forms, you'll want to check the React Router 7 Official Documentation for how they integrate these actions into their routing lifecycle.
HMR: The Secret Sauce of RSC Development
Hot Module Replacement (HMR) is what makes Vite feel fast. In a standard React app, when you change a file, Vite sends a message to the browser via WebSockets, and the browser replaces that module. With RSC, HMR becomes a multi-step dance.
- File Change: You edit
ProductList.tsx(a Server Component). - RSC Invalidation: Vite invalidates the module in the
rscenvironment graph. - Re-execution: The server re-runs the RSC logic for that component.
- Payload Streaming: The server generates a new RSC payload.
- Browser Update: The browser receives the new payload and "reconciles" it.
The beauty of this approach is that it preserves client-side state. If you have a search input with text in it (a Client Component) and you change the background color of a Server Component parent, the search text stays. The browser doesn't reload; it just patches the DOM based on the new RSC stream. This streaming process relies heavily on the MDN Web Streams API Reference to process data as it arrives, rather than waiting for the whole page to render.
At FutureStack, we often see developers struggle with HMR when they have circular dependencies between Server and Client components. Vite will usually throw a "Circular dependency" warning. To fix this, always ensure your data flows one way: Server -> Client. If a Client Component needs to trigger a Server update, use a Server Action or a URL state change, rather than trying to import a Server Component into a Client file.
Debugging the RSC Environment in Production
When you move from dev to production, the Vite Environment API transitions from a dev server to a build pipeline. The biggest hurdle here is "Module Resolution." In dev, Vite can resolve files on the fly. In production, every Client Component must be pre-bundled and assigned a "Manifest ID."
If your RSC environment tries to render a Client Component that isn't in the manifest, the whole app fails. This usually happens when you use dynamic imports (import()) inside an RSC. You must ensure that your build step generates a client-manifest.json that the server can read at runtime to map component names to their actual JS filenames.
import { renderToReadableStream } from 'react-server-dom-webpack/server';
import { App } from './App';
// This function runs on the server for every request
export async function handleRequest(req: Request) {
// 1. Fetch data based on the request
// 2. Render the component tree to the RSC "Flight" format
const stream = renderToReadableStream(
<App />,
// The manifest tells React which JS files the client needs to download
// for the 'use client' components found in the tree
globalThis.CLIENT_MANIFEST
);
return new Response(stream, {
headers: { 'Content-Type': 'text/x-component' },
});
}This manual orchestration is exactly what frameworks like Next.js hide from you. But by using Vite directly, you gain control over the caching layer. You can implement fine-grained invalidation strategies that aren't possible in a locked-down framework. For more on how to manage this data layer, see our guide on Caching in React Server Components: Mastering use cache, Partial Prerendering, and Revalidation.
When things go wrong in the RSC environment, the error messages are often cryptic. You might see Error: Objects are not valid as a React child. This usually means you accidentally tried to render a Promise or a complex class-based object that can't be serialized. Always stick to POJOs (Plain Old JavaScript Objects) when passing data from the RSC environment to the Client. If you need to verify the integrity of the data being passed, especially when dealing with authentication tokens, our Free JWT & Crypto Security Workbench can help you debug the payloads being sent across the wire.
By mastering the Vite Environment API, you aren't just using a tool; you are building a custom engine. You can decide exactly how your SSR and RSC environments interact, which is the key to building high-performance applications that don't suffer from the "framework bloat" often associated with modern React development.
3. Hands-On with Waku: The Minimalist RSC Framework
Next.js often feels like a "black box" that handles everything from image optimization to complex caching layers. If you want to understand how React Server Components (RSC) actually function at a granular level, you use Waku. Created by Daishi Kato—the mind behind Jotai and Zustand—Waku is the most lightweight way to run RSC today. It strips away the enterprise bloat and gives you a raw, Vite-powered environment where the server and client boundaries are crystal clear.
I often tell my team at FutureStack that Waku is the "un-framework." It doesn't force a specific styling library or a rigid middleware structure on you. It focuses on the core problem: how to stream serialized React elements from a server to a browser without a massive JavaScript bundle. Before we write a single line of code, you should check our React Server Components (RSC) Glossary Reference to ensure you’re comfortable with terms like "Flight Stream" and "Serialization," as Waku exposes these concepts directly.
3.1 Architecture: The pages/ Directory and the Vite Engine
Waku leverages the Vite Environment API Documentation to manage two separate build graphs: one for the server and one for the client. In a standard Waku project, your entry point is usually src/entries.tsx. This file defines how your routes are mapped to components. Unlike Next.js, which uses a complex file-system router with layout.tsx and page.tsx files scattered everywhere, Waku’s createPages API allows you to define your structure programmatically or via a simplified pages/ directory.
When you build a blog or a product catalog in Waku, every file inside src/pages is a Server Component by default. You don't need to add a "use server" directive at the top of these files; the environment assumes they run on the server. If you need interactivity—like a search bar or a "Buy Now" button—you must explicitly create a separate component file with the "use client" directive.
[!IMPORTANT]
In Waku, if you accidentally import a heavy Node-only library (like fs or path) into a component that ends up in a Client Island, the build will fail. This is a feature, not a bug. It prevents you from leaking server secrets or bloating the browser bundle.
Let’s look at how we set up a data-heavy catalog page. We’ll fetch data from a database directly inside the component. For this example, I’m assuming a Supabase backend, though you can compare options in our PostgreSQL vs. Supabase Architecture Benchmark to see which fits your scale.
import { Suspense } from 'react';
import { ProductCard } from '../components/ProductCard.js';
import { SkeletonGrid } from '../components/SkeletonGrid.js';
// This is a pure React Server Component.
// It runs ONLY on the server. No JS for this component is sent to the browser.
async function ProductList() {
// Direct database access. No internal API fetch needed.
const response = await fetch('https://api.example.com/products', {
next: { revalidate: 60 } // Waku supports standard fetch extensions
});
const products = await response.json();
return (
<div className="grid grid-cols-3 gap-4">
{products.map((product: any) => (
/* ProductCard can be a Client Component if it has 'Add to Cart' logic */
<ProductCard key={product.id} item={product} />
))}
</div>
);
}
export default function HomePage() {
return (
<main className="max-w-4xl mx-auto p-8">
<h1 className="text-3xl font-bold mb-6">Engineering Hardware Catalog</h1>
<Suspense fallback={<SkeletonGrid />}>
<ProductList />
</Suspense>
</main>
);
}3.2 Handling Interactivity with Server Functions
The real magic happens when you need to change data. In the old world, you’d write an API route, handle POST requests, manage loading states with useState, and manually trigger a re-validation. Waku implements the React 'use server' Server Functions Guide (react.dev) specification perfectly.
Suppose we want to add a "Like" feature to our catalog. We don't want a full page reload, and we don't want to manage a complex Redux store. We use a Server Function. This is a function defined with the "use server" directive that the client can call as if it were a local function. Under the hood, Waku handles the HTTP POST and the serialization of the arguments.
One mistake I see senior devs make is putting too much logic inside the "use client" boundary. If you aren't careful, you’ll end up sending 500KB of Framer Motion or Chart.js to the user just for a simple toggle. I highly recommend reading The "use client" Boundary Trap: 7 React Server Component Mistakes That Bloat Your Bundle to avoid these common pitfalls in Waku.
Here is how you implement a secure, type-safe Server Function for a comment form in Waku:
'use client'; // This is a Client Island
import { useActionState } from 'react';
import { addComment } from '../actions/comments.js';
export function CommentForm({ productId }: { productId: string }) {
// useActionState is the modern way to handle form submissions in RSC
// Reference: https://react.dev/reference/react/useActionState
const [state, formAction, isPending] = useActionState(addComment, {
message: '',
error: null,
});
return (
<form action={formAction} className="mt-8 space-y-4">
<input type="hidden" name="productId" value={productId} />
<textarea
name="content"
className="w-full border p-2 rounded"
placeholder="Leave a technical review..."
required
/>
<button
type="submit"
disabled={isPending}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:bg-gray-400"
>
{isPending ? 'Posting...' : 'Post Comment'}
</button>
{state.error && <p className="text-red-500">{state.error}</p>}
{state.message && <p className="text-green-600">{state.message}</p>}
</form>
);
}And the corresponding server-side logic:
'use server'; // This marks the file as containing Server Functions
import { db } from '../lib/db.js';
import { revalidatePath } from 'waku/server';
export async function addComment(prevState: any, formData: FormData) {
const content = formData.get('content') as string;
const productId = formData.get('productId') as string;
// Security: Always validate input on the server
if (!content || content.length < 5) {
return { message: '', error: 'Comment too short.' };
}
try {
await db.insert('comments').values({ content, productId });
// This tells Waku to refresh the RSC stream for this page
revalidatePath(`/product/${productId}`);
return { message: 'Comment added successfully!', error: null };
} catch (e) {
return { message: '', error: 'Database connection failed.' };
}
}3.3 Deployment: From Node to the Edge
Waku’s build output is remarkably clean. When you run npm run build, it generates a dist folder containing a public directory (for static assets) and a server directory. Unlike Next.js, which requires a specific runtime or a complex adapter for every platform, Waku is built to be environment-agnostic.
You have three primary paths for deployment:
- Node.js / Docker: The simplest path. You run a small Express or Hono server that imports the Waku middleware. This is ideal if you have a heavy dependency on native Node modules.
- Cloudflare Workers: Because Waku doesn't rely on massive internal caches that require filesystem access, it fits comfortably within the 1MB script limit of Cloudflare Workers. It uses the standard Web Fetch API for requests and responses.
- Vercel/Netlify: Waku has built-in presets for these platforms, utilizing their respective Edge Function capabilities.
| Feature | Waku (Minimalist) | Next.js (Enterprise) |
|---|---|---|
| Bundle Size | Extremely Small (Vite-optimized) | Large (includes framework runtime) |
| Routing | Programmatic or simple pages/ | File-system based app/ directory |
| Data Fetching | Standard fetch + RSC | fetch with deep cache integration |
| Learning Curve | Low (if you know Vite/React) | High (due to many abstractions) |
| Cold Starts | Fast (minimal JS to parse) | Slower (more framework code to init) |
3.4 Production Edge Cases: What Breaks?
In my production testing, Waku shines in performance but requires more "manual" work than Next.js. For instance, Waku doesn't automatically handle image optimization. If you serve a 5MB hero image, Waku won't resize it for you. You’ll need to use a service like Cloudinary or Unpic.
Another catch is the Module Resolution. Waku is strict about ESM (ES Modules). If you try to import an old CommonJS library that doesn't play nice with Vite, you will see errors like module is not defined. You’ll often find yourself adding ssr.noExternal to your vite.config.ts to force certain packages to be bundled correctly.
Lastly, pay attention to Environment Variables. Since Waku uses Vite, you must prefix client-side variables with VITE_. However, server-side secrets should never have this prefix. On the server, Waku accesses variables via process.env (in Node) or the env object (in Cloudflare Workers). Mixing these up is a common way to leak API keys.
By using Waku, you aren't just building an app; you're building a deep understanding of how the future of React works. You see the Flight stream in the Network tab. You see exactly when a component transitions from a server-side string to a client-side interactive element. It is the purest expression of "React Server Components without Next.js" available today.
4. Hands-On with React Router 7 in RSC Mode
React Router 7 (the unified successor to Remix) changes the game for teams who want React Server Components but aren't ready to buy into the full Next.js ecosystem. For years, we used React Router to build Single Page Applications (SPAs) where the browser did all the heavy lifting. Then Remix showed us how to move data fetching to the server using loader functions. Now, React Router 7 bridges the final gap: it allows those loaders to return actual Server Component JSX trees.
This is a massive shift in mental models. In a traditional React Router app, your loader returns a JSON object. The client receives that JSON, triggers a re-render, and populates the UI. In RSC mode, the server can render the complex, data-heavy parts of your UI and stream them to the client. This reduces the amount of JavaScript the browser has to parse and execute, which directly improves your web.dev Largest Contentful Paint (LCP) Guide scores.
The "Single Fetch" and Component-as-Data Pattern
The core innovation in React Router 7's RSC implementation is how it handles the "Network Boundary." Usually, when you navigate in a React app, the browser makes a request for the component code, then another request for the data (the loader), and finally renders. This creates a staggered loading experience.
With React Router 7, the framework uses a "Single Fetch" mechanism. When a user clicks a link, the router sends one request to the server. The server executes the loader, fetches the data, and renders the Server Components into a streamable format (RSC payload). The client receives this single stream and updates the page.
This approach is perfect for migrating large codebases. You don't have to rewrite your entire app. You can keep your existing client-side state management, like TanStack Query Official Documentation, for interactive features while moving static, data-rich sections to Server Components.
import { Suspense } from "react";
import { useLoaderData } from "react-router";
import { getProductAnalytics } from "~/lib/api.server";
import { AnalyticsChart } from "~/components/charts.client"; // Interactive client component
import { DataGrid } from "~/components/grid.server"; // Static server component
// 1. The loader runs ONLY on the server in RR7 RSC mode.
// It can now return a mix of raw data and pre-rendered Server Components.
export async function loader({ request }: { request: Request }) {
const stats = await getProductAnalytics();
// We return the data needed for the client chart
// AND the heavy Server Component for the grid.
return {
stats,
gridElement: <DataGrid data={stats.rawRows} />
};
}
export default function DashboardRoute() {
const { stats, gridElement } = useLoaderData<typeof loader>();
return (
<main className="p-8">
<h1>Project Analytics</h1>
{/* 2. Client-side interactivity remains fast */}
<div className="h-64 mb-8">
<AnalyticsChart data={stats.summary} />
</div>
{/* 3. The heavy grid was rendered on the server.
The client just 'slots' it in without needing the grid's JS logic. */}
<Suspense fallback={<p>Loading detailed records...</p>}>
{gridElement}
</Suspense>
</main>
);
}Progressive Migration: From JSON to RSC
One of the biggest mistakes I see engineering leads make is trying to flip a "big switch" from SPA to RSC. It almost always results in broken production environments and frustrated developers. React Router 7 allows for a "Route-by-Route" migration.
In a standard SPA, your loader might look like this: return json({ user: data }). To move toward RSC, you change your route configuration to enable the v7_serverComponents flag. Once enabled, your loader can return JSX. This is particularly useful for Eliminating Request Waterfalls in React Server Components with Parallel Streaming & Suspense because you can start streaming parts of the page before the entire data fetch is complete.
The mental model shifts from "fetching data for a component" to "the server providing the component itself." If you have a complex sidebar with nested permissions and deep database calls, don't send that logic to the client. Render it in the loader, return the JSX, and let the browser act as a simple rendering engine.
[!IMPORTANT] When passing data from a server loader to a client component in React Router 7, ensure you aren't accidentally leaking sensitive environment variables or database keys. Use the React experimental_taintObjectReference Security API (react.dev) to mark sensitive objects so they can never be passed to the client boundary.
Handling Edge Cases: Hydration Mismatches and State
When you start returning Server Components from loaders, you will eventually hit a hydration mismatch. This usually happens when the server renders something (like a timestamp or a random ID) that changes by the time the client tries to take over.
In React Router 7, the boundary between the server-rendered gridElement (from our code example above) and the client-rendered AnalyticsChart is strict. The client doesn't "hydrate" the gridElement; it simply places the pre-rendered HTML into the DOM. This is why RSC is so much faster for heavy UI—the browser doesn't have to re-verify the structure of that HTML against a JavaScript bundle.
However, if your DataGrid (the server component) needs to respond to a search input in the AnalyticsChart (the client component), you must use URL search parameters. This is the "Web Standards" way that React Router 7 enforces. Instead of using a useState hook to filter the grid, you update the URL: ?search=iphone. This triggers the server loader to re-run, fetch filtered data, and send back a new gridElement.
| Feature | React Router 7 (RSC Mode) | Next.js (App Router) |
|---|---|---|
| Data Fetching | loader functions (Server-only) | async Components + fetch |
| State Management | URL-first, standard React State | URL-first, use server actions |
| Routing | Config-based or File-based | Strictly File-based (page.tsx) |
| Bundle Size | Smaller (No router logic in RSCs) | Varies (Heavier framework runtime) |
| Deployment | Any Node/Edge provider | Optimized for Vercel |
Implementing Parallel Data Fetching
A common bottleneck in large-scale applications is waiting for three different API calls to finish before showing anything to the user. In the Full-Stack Next.js 2026 Engineering Roadmap, we discussed how the industry is moving toward "Render-as-you-fetch." React Router 7 implements this beautifully.
By using React Suspense Streaming Reference (react.dev), you can return "deferred" promises from your loader. The server will send the shell of the page immediately and keep the HTTP connection open. As the promises resolve, the server renders the remaining Server Components and "pushes" them down the wire.
// Data Access Layer (DAL) - Always runs on server
import { cache } from "react";
// We use React's cache to deduplicate requests
// during a single render cycle.
export const getSlowMarketingData = cache(async () => {
// Simulate a slow legacy API call
await new Promise((res) => setTimeout(res, 2000));
return { leadGen: "Active", campaign: "Winter 2024" };
});
export const getFastUserData = async (userId: string) => {
// Direct database query
return await db.user.findUnique({ where: { id: userId } });
};In the route file, you would combine these. The getFastUserData might be awaited (blocking the initial render so the user sees their name immediately), while getSlowMarketingData is passed as a promise to a Server Component wrapped in <Suspense>. This ensures the user isn't staring at a white screen for 2 seconds.
Deployment and Infrastructure Considerations
Unlike Next.js, which has specific optimizations for Vercel's infrastructure (like the Next.js 'use cache' Directive Reference), React Router 7 is designed to be infrastructure-agnostic. You can host your RSC-powered app on a standard Node.js server, a Docker container, or even at the edge.
When deploying to an Edge Computing Architecture Glossary provider like Cloudflare Workers, the RSC streaming becomes even more powerful. Because the server is physically closer to the user, the "Time to First Byte" (TTFB) for your RSC payload is significantly lower. React Router 7's small runtime footprint makes it ideal for these constrained environments where every millisecond of execution time costs money.
I've found that debugging RSC in React Router 7 is often easier than in Next.js because the data flow is more explicit. You know exactly when the loader runs. You can see the __rv-data (React Router Data) requests in the browser's Network tab. If a Server Component isn't rendering, you check the loader. There's no "magic" background revalidation that's hard to trace—it's just standard HTTP requests and responses.
If you are currently managing a large React Router SPA and feeling the pressure to move to RSC for performance reasons, don't rewrite. Start by upgrading to v7, enable the server flags, and move your most expensive data-fetching component into a loader. You'll see the bundle size drop and the interactivity speed up almost immediately.
5. Building a Minimal Custom Vite + Hono RSC Server (Educational Blueprint)
Most developers think React Server Components (RSC) are a feature of Next.js. They aren't. RSC is a primitive built into the React library itself. When you use a framework, you are using a pre-configured "bundler + router + server" stack that hides the plumbing. To truly master react server components without nextjs, we need to look at the plumbing.
In this chapter, we will build a "naked" RSC implementation. We are going to use Vite for bundling, Hono as our web server, and the official react-server-dom-webpack package to handle the heavy lifting of the Flight wire protocol. This exercise isn't about building a production framework—it's about understanding why your code works so you can debug it when things break in production.
The Anatomy of an RSC Request
When a user visits your app, two distinct things happen. First, the server needs to render the initial HTML so the user sees something immediately. Second, the server needs to generate a serialized stream of data (the RSC payload) that React on the client uses to build the component tree and handle updates without a full page reload.
Think of the RSC payload as a set of instructions. Instead of sending HTML or raw JSON data, the server sends a stream that says: "At this point in the tree, render a <div>. Inside that, render a component called ClientCounter which you can find at this URL, and pass it these props."
I have seen many teams struggle because they treat RSC like a standard API call. It isn't. If you want to see the specific format of these instructions, you should read our guide on React Server Components Explained: Inside the RSC Flight Wire Protocol. Understanding the "Flight" format is the difference between guessing why a component didn't render and knowing exactly which module reference failed.
Setting Up the Hono Server Entry
Hono is the perfect choice for a custom RSC server because it is lightweight and runs anywhere—Node.js, Bun, or Cloudflare Workers. Our server has one primary job: take a request, decide which Server Component to render, and pipe the result to the browser.
The most confusing part for beginners is the moduleMap. React needs to know which "Client Components" (marked with 'use client') are used inside your Server Components. Since the server only deals with the logic, it needs a manifest to tell the client: "Hey, I found a client component here; go fetch its JavaScript file from the /dist folder."
import { Hono } from 'hono';
import { renderToReadableStream } from 'react-server-dom-webpack/server.edge';
import { serveStatic } from '@hono/node-server/serve-static';
import App from './App.js'; // Your root Server Component
const app = new Hono();
// 1. Serve static assets (JS, CSS) from the build folder
app.use('/static/*', serveStatic({ root: './dist' }));
// 2. The RSC Endpoint
app.get('/rsc', async (c) => {
// In a real app, you'd load this manifest from a JSON file generated by Vite
const moduleMap = {};
// transform the React tree into a serialized stream
const stream = renderToReadableStream(<App />, moduleMap);
return c.body(stream, {
headers: {
'Content-Type': 'text/x-component',
},
});
});
// 3. The Initial HTML Shell
app.get('/', (c) => {
return c.html(`
<!DOCTYPE html>
<html>
<head><title>Custom RSC</title></head>
<body>
<div id="root"></div>
<!-- This script boots up the client-side React runtime -->
<script type="module" src="/static/client.js"></script>
</body>
</html>
`);
});
export default app;[!IMPORTANT]
The package name react-server-dom-webpack is misleading. Even though it says "webpack," it is the standard package used for Vite and other bundlers to handle the RSC stream serialization. Don't let the name scare you away from using it in a Vite-based project.
Wiring Vite for the Server and Client
To make react server components without nextjs work, you actually need two separate build steps. One build handles the "Server Environment" (your .tsx files that fetch data) and another handles the "Client Environment" (your 'use client' components).
Vite recently introduced the Vite Environment API Documentation which makes this much easier. You have to tell Vite to treat your server code differently, ensuring it doesn't try to bundle browser-only APIs like window or document into your server-side logic.
When building your custom pipeline, you will often run into an error like ReferenceError: exports is not defined. This usually happens because a library you're using is still using CommonJS, but RSC requires strict ESM (ES Modules). I recommend using the Free Client-Side JSON to TypeScript & Zod Schema Generator to create strict types for the data your server components fetch. This prevents "undefined" errors from propagating through the RSC stream, which are notoriously hard to trace.
The Client-Side "Consumer"
The browser doesn't know how to read the text/x-component stream by itself. We need to use createFromReadableStream from the react-server-dom-webpack/client package. This function takes the fetch response and turns it back into a React element tree that can be rendered into the DOM.
import { createRoot } from 'react-dom/client';
import { createFromReadableStream } from 'react-server-dom-webpack/client';
// 1. Fetch the RSC stream from our Hono server
const response = fetch('/rsc');
// 2. Convert the stream into a React element
// The second argument would be the 'moduleMap' for resolving client components
const rootElement = createFromReadableStream(response);
// 3. Render the result into the page
const root = createRoot(document.getElementById('root')!);
root.render(rootElement);Comparing RSC Architectures
When you move away from Next.js, you gain control but lose the "automatic" optimizations. Here is how a custom Vite + Hono setup compares to the standard Next.js App Router.
| Feature | Next.js (App Router) | Custom Vite + Hono |
|---|---|---|
| Routing | File-system based (built-in) | Manual (Hono or React Router 7) |
| Bundling | Webpack/Turbopack (Hidden) | Vite Environment API (Explicit) |
| Data Fetching | fetch cache overrides | Standard native fetch |
| Deployment | Vercel-optimized | Any JS runtime (Node, Bun, Edge) |
| Complexity | Low (Abstractions) | High (Full control) |
Handling Security and Data Leaks
In a custom setup, security is entirely on you. In Next.js, the framework handles a lot of the sanitization when passing props from Server to Client components. When building your own, you must be extremely careful not to pass sensitive objects (like database connection strings or private user emails) through the RSC stream.
The RSC stream is essentially a public API. If you pass a prop to a client component, that prop is visible in the network tab to anyone who knows how to look. I highly recommend reviewing the OWASP Top 10 Web Application Security Risks and our specific guide on React Server Components Security: Preventing Data Leaks, IDOR, and Server Action Exploits.
One common mistake I see is passing a full "User" object from a database query directly into a UserAvatar client component. Even if the avatar only uses the imageUrl, the entire object—including the hashedPassword or internalId—might be serialized into the Flight stream. Always "strip" your data before it leaves the server boundary.
Debugging the "Hydration Mismatch" in Custom RSC
One of the most frustrating errors you'll hit is the "Hydration Mismatch." This happens when the HTML generated by the server doesn't match what the client thinks the initial state should be.
In a custom RSC setup, this often happens because of a mismatch in the moduleMap. If your server thinks a client component is located at /dist/components/Button.js but your Vite dev server serves it at /src/components/Button.tsx, React will lose its mind.
[!TIP]
When debugging hydration issues in a custom RSC setup, always check the __webpack_require__ calls in the network stream. If the path in the stream doesn't match the actual URL of your JS chunks, your client components will simply never appear, or worse, they will throw a "Module not found" error that crashes the whole tree.
Why go through this trouble?
You might ask: "Arham, why wouldn't I just use Next.js?"
The answer is portability. By building a minimal RSC server with Hono, you can deploy your application to the extreme edge. You aren't tied to Vercel's infrastructure or the specific version of React that Next.js forces on you. You can use the latest experimental features of React 19, like the React useActionState Hook Reference (react.dev), without waiting for a framework update.
This custom approach is the foundation of "Edge-First" systems. If you are interested in how this fits into a larger microservices strategy, check out our piece on Edge-First Systems: Building Resilient Microservices with Next.js 15 & Turbopack. Even though that guide mentions Next.js, the architectural principles of moving logic to the edge apply perfectly to a Hono + RSC setup.
Implementing Server Functions ('use server')
To make your custom server interactive, you need to handle Server Actions. This requires another endpoint on your Hono server that listens for POST requests. When a user submits a form, the browser sends a request with a special header (like rsc-action). Your server must look up the function associated with that ID, execute it, and then—crucially—return the updated RSC stream so the UI updates in one round trip.
This "Action -> Re-render" loop is what makes RSC feel like a single-page app even though the logic stays on the server. You can follow the React 'use server' Server Functions Guide (react.dev) to see the expected function signatures, but remember that in a custom setup, you are responsible for the "Action Registry" that maps a random string ID to your actual TypeScript function.
In the next chapter, we will look at how React Router 7 (formerly Remix) automates this plumbing while still giving you more control than Next.js. We'll see how they bridge the gap between the "naked" implementation we just built and a production-ready developer experience.
6. Head-to-Head Comparison: Next.js vs. Waku vs. React Router 7 vs. Custom Vite
Choosing a framework for React Server Components (RSC) is not just about choosing a syntax. It is about choosing how your code is bundled, where it can be hosted, and how much "magic" you are willing to debug at 2 AM. When we build systems at FutureStack, we look at the long-term maintenance cost. Next.js is the giant in the room, but Waku, React Router 7, and custom Vite setups offer radically different engineering paths.
The following comparison is based on production deployments where we moved a high-traffic dashboard from Next.js to a custom Vite RSC implementation to reduce cold starts. We found that while Next.js provides everything out of the box, the "everything" often includes a lot of weight you might not need.
The Engineering Trade-off Matrix
This table breaks down the core differences. "DX" refers to how much manual boilerplate you have to write to make a Server Component talk to a Client Component.
| Feature | Next.js (App Router) | Waku | React Router 7 | Custom Vite RSC |
|---|---|---|---|---|
| Build Engine | Webpack (moving to Turbo) | Vite | Vite | Vite |
| RSC Maturity | Production-hardened | Experimental/Bleeding edge | Stable (via Remix heritage) | "Build it yourself" |
| Caching Strategy | Aggressive, Vercel-centric | Minimal, manual | Loader-based / Standard Web | Manual / Cache-Control |
| Hosting | Optimized for Vercel | Any Node/Edge provider | Extremely portable | Any Docker/Node env |
| Bundle Size | Heavy (Framework overhead) | Ultra-light | Moderate | Minimalist |
| Cold Starts | 500ms - 2s (Node.js) | <200ms (Edge-ready) | <300ms | <150ms |
Build Speed and Developer Experience (DX)
Next.js uses a sophisticated but heavy build process. Even with Turbopack, the complexity of managing the "Server" and "Client" graphs in Webpack is significant. In a large project with 500+ components, we've seen Next.js dev server starts take 15–20 seconds. In contrast, Waku and React Router 7 leverage Vite’s native ESM HMR (Hot Module Replacement).
When you use Vite, the dev server starts almost instantly because it doesn't bundle everything upfront. It serves files as the browser requests them. This is a massive win for developer productivity. However, the trade-off is that React Server Components vs. SSR: Why They Solve Completely Different Problems because RSC requires a specialized "Flight" stream that Vite does not handle natively without a plugin like @vitejs/plugin-react.
In a custom Vite setup, you have to manage the react-server export condition yourself. If you forget to set this in your package.json or Vite config, your server components will try to run with client-side React logic, leading to the infamous Error: Cannot find module 'react-dom/server' in environments where you least expect it.
// This example shows how Waku handles data isolation
// compared to the heavy 'use cache' logic in Next.js.
import { Suspense } from 'react';
// In Waku, this function stays strictly on the server.
// No need for complex 'use cache' directives for simple fetches.
async function UserProfile({ id }: { id: string }) {
const res = await fetch(`https://api.futurestack.online/users/${id}`, {
// We use standard Web API cache headers here
next: { revalidate: 60 } // Only if using a Next-compatible fetch polyfill
});
if (!res.ok) throw new Error('Failed to fetch user');
const user = await res.json();
return (
<div className="p-4 border rounded shadow">
<h2 className="text-xl font-bold">{user.name}</h2>
<p className="text-gray-600">{user.email}</p>
</div>
);
}
export default function Dashboard({ userId }: { userId: string }) {
return (
<section>
<h1>Project Dashboard</h1>
{/*
We use standard React Suspense for streaming.
Reference: https://react.dev/reference/react/Suspense
*/}
<Suspense fallback={<p>Loading profile...</p>}>
<UserProfile id={userId} />
</Suspense>
</section>
);
}Caching Primitives and Data Flow
Next.js has built a custom caching layer that is deeply integrated with Vercel’s Infrastructure. While the Next.js 'use cache' Directive Reference makes it easy to persist data, it can feel like a black box. If a cache doesn't invalidate, you are often left purging the entire CDN.
React Router 7 (the successor to Remix) takes a different approach. It uses "Loaders" that can run on the server, but it is moving toward a model where RSCs can handle their own data fetching. The beauty of React Router 7 is that it treats the URL as the primary source of truth. It doesn't try to hide the network.
If you are building a custom RSC implementation with Vite, you will likely need to integrate something like TanStack Query Official Documentation for the client-side state, while keeping your server-side fetches simple. The challenge here is "Waterfall" prevention. Without a framework like Next.js or Waku managing the manifest, it is easy to accidentally trigger sequential fetches that kill your web.dev Largest Contentful Paint (LCP) Guide scores.
[!WARNING] When building custom RSC setups, avoid passing large, complex objects from Server to Client. Every prop passed across the "Server-Client Bridge" must be serializable. If you pass a class instance or a function, the build will fail or, worse, throw a runtime error that is hard to trace in minified production code.
Hosting Portability and Vendor Lock-in
This is where the "Without Next.js" path shines. Next.js is technically open-source and can be self-hosted via Docker, but features like Image Optimization, Middleware at the Edge, and ISR (Incremental Static Regeneration) require significant manual configuration on platforms like AWS or DigitalOcean.
Waku and React Router 7 are designed to be "adapter-agnostic." You can deploy a Waku app to Cloudflare Workers, Deno Deploy, or a standard Node.js VPS with almost zero config changes. This is because they rely on standard Web Streams and Request/Response objects rather than Node-specific internals.
When we look at the Vercel vs. Netlify Edge Architecture Comparison, we see that using a Vite-based RSC framework allows you to switch providers in minutes. For a startup, this flexibility is a massive hedge against price hikes or platform instability.
Security: The "Taint" API and Data Leaks
One often-overlooked aspect of RSC is security. When you fetch data on the server and pass it to a client component, it is incredibly easy to accidentally send a hashed password or a private API key to the browser.
Next.js provides some protection, but in a custom Vite or Waku setup, you must be disciplined. You should use the React experimental_taintObjectReference Security API (react.dev) to explicitly block sensitive objects from being passed to the client.
// Data Access Layer (DAL) with Security Tainting
import { experimental_taintObjectReference } from 'react';
export async function getUserSession(sessionId: string) {
const session = await db.sessions.findUnique({ where: { id: sessionId } });
if (session) {
// This prevents the entire session object from being passed
// to a 'use client' component. If you try, React throws an error.
experimental_taintObjectReference(
'Do not pass raw session objects to the client!',
session
);
}
return session;
}Maintenance and Team Scaling
If you have a junior-heavy team, Next.js is the safest bet. The documentation is vast, and most "how-to" questions are already answered on StackOverflow. However, you will spend time fighting the framework's opinions on how to structure your folders and how to handle redirects.
Waku is perfect for small, high-performance teams who want the absolute smallest bundle size. It feels like writing "Vanilla React" again. There is no next/image or next/font to learn—just standard HTML and CSS.
React Router 7 is the middle ground. It is the best choice if you are migrating a legacy React SPA (Single Page Application). You can keep your existing routes and slowly introduce Server Components where they make sense (like for heavy data-processing pages).
For those choosing the "Custom Vite" route, be prepared to write your own register.js for the server and manage the react-server-dom-vite plugin yourself. It is a rewarding path for systems architects but a nightmare for teams that just want to ship features. You will need to handle Caching in React Server Components: Mastering use cache, Partial Prerendering, and Revalidation manually by setting headers on your Vite dev server and production Express/Fastify server.
Final Verdict for Chapter 6
- Choose Next.js if you need a "batteries-included" experience and are comfortable with Vercel's ecosystem.
- Choose Waku if you want the fastest possible RSC performance and a minimalist developer experience.
- Choose React Router 7 if you are building a complex, route-heavy application and want a stable, battle-tested foundation.
- Choose Custom Vite only if you are building a specialized platform (like a CMS or a specialized dashboard) where you need total control over the build pipeline and zero framework overhead.
In the next chapter, we will look at the actual deployment scripts and CI/CD pipelines required to get these non-Next.js RSC apps into production without breaking the bank on cloud costs.
7. Deployment & Self-Hosting Guide (Docker, Fly.io, Cloudflare, Netlify)
Deploying React Server Components (RSC) without the "Vercel safety net" feels intimidating at first. When you use Next.js, the framework hides the complexity of how server-side code is bundled, how the manifest is mapped, and how the stream is delivered to the browser. But when you move to a custom Vite-based setup or use a library like Waku, you gain full control over the infrastructure. This control is a double-edged sword. You can optimize your server for specific regions or lower your costs significantly, but you also have to configure the plumbing yourself.
I’ve spent the last six months breaking and fixing RSC deployments on everything from tiny Raspberry Pis to massive Kubernetes clusters. The most common failure isn't the code itself; it's the environment. If your reverse proxy buffers the response, your users won't see the benefits of React Suspense Streaming. If your Docker image doesn't preserve the build-time manifest, your client components will simply fail to hydrate.
The Multi-Stage Docker Strategy for Portable RSCs
Standard Node.js Dockerfiles usually just copy everything and run npm start. That won't work for a custom RSC setup. You need a multi-stage build that treats the "Server" and "Client" as two distinct but linked artifacts. In a project using Vite or Waku, the build process generates a server entry point and a client manifest. The server needs that manifest to know which chunks to tell the browser to download.
If you lose that mapping during the docker build process, you'll see the dreaded "Module not found" error in the browser console, even though the file exists on the server. This happens because the hash in the filename changed, but the server is still looking for the old version.
Here is a production-ready Dockerfile I use for Vite-based RSC applications. It ensures the environment is clean and the build artifacts are strictly separated from the source code to keep image sizes under 200MB.
# Stage 1: Build the application
FROM node:20-slim AS builder
WORKDIR /app
# Install build dependencies
COPY package.json package-lock.json ./
RUN npm ci
# Copy source and build the RSC app
# This step generates the /dist folder containing
# both 'client' and 'server' subdirectories.
COPY . .
RUN npm run build
# Stage 2: Production runner
FROM node:20-slim AS runner
WORKDIR /app
# Set production environment
ENV NODE_ENV=production
# Important: Ensure the server listens on all interfaces inside the container
ENV HOST=0.0.0.0
ENV PORT=3000
# Only copy the necessary artifacts from the builder
# We need the production node_modules and the dist folder
COPY --from=builder /app/package.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
# Most custom RSC setups (like Waku) use a specific entry point
# for the production server. Adjust this to your framework's entry.
EXPOSE 3000
CMD ["node", "dist/server/index.js"][!IMPORTANT]
When running "react server components without nextjs" in Docker, always ensure your .dockerignore excludes your local node_modules and dist folders. If you accidentally copy your local Mac/Windows build into a Linux container, the native dependencies (like Sharp or database drivers) will crash with a "not a valid Win32 application" or "ELF header" error.
Solving the "Buffering" Nightmare in Reverse Proxies
The killer feature of RSC is streaming. Instead of waiting for the whole page to generate, the server sends the shell immediately and streams in the slow data as it resolves. However, if you put your Docker container behind Nginx, Caddy, or a Load Balancer without the right settings, the proxy will "helpfully" wait until the stream is finished before sending anything to the user. This turns your fast RSC app back into a slow, traditional SSR app.
I once spent four hours debugging why a dashboard was taking 5 seconds to show anything, even though I used <Suspense>. It turned out Nginx was buffering the response. To fix this, you must disable proxy buffering.
For Nginx, you need the X-Accel-Buffering header or a specific configuration block. If you are using a custom Vite-based server, you can also send this header directly from your Node.js response object.
// In your custom server entry (Express, Fastify, or Hono)
export function streamingMiddleware(req, res, next) {
// This header tells Nginx and other proxies NOT to buffer the response.
// Without this, React Suspense chunks won't appear until the end.
res.setHeader('X-Accel-Buffering', 'no');
// Standard header for streaming content
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
next();
}If you prefer to handle this at the Nginx level, your nginx.conf should look like this:
location / {
proxy_pass http://rsc_app:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# Critical for React Server Component Streaming
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
chunked_transfer_encoding on;
}Self-Hosting vs. Edge: Fly.io, Cloudflare, and Netlify
When you aren't tied to Vercel, you have to choose your "runtime" carefully. Not all "react server components without nextjs" setups work the same way across different providers.
1. Fly.io (The "Full Server" Approach)
Fly.io is my top recommendation for self-hosting RSCs. It runs your Docker container as a "Firecracker microVM." This means you have a real Node.js environment. You can use long-lived database connections, access the file system, and use any NPM package without worrying about "Edge" limitations.
The main trade-off here is the "Cold Start." If you scale your app to zero to save money, the first user might wait 2–3 seconds for the VM to boot. For RSC, this is painful because the user sees a blank screen during the boot, then the shell, then the streamed content. I recommend keeping at least one instance "always on" in your primary region.
2. Cloudflare Workers (The "Edge" Approach)
Running RSC on Cloudflare Workers is incredibly fast because the code runs physically close to the user. However, you are restricted to the workerd runtime, not Node.js. This means no fs module and no native C++ bindings.
When deploying Vite-based RSCs to the edge, you must ensure your build target is set to webworker. You'll also need to be careful with the React 'use server' Server Functions Guide. If your server function tries to connect to a traditional PostgreSQL database without a proxy like Prisma Accelerate or Supabase's connection pooler, it will fail because standard TCP sockets are restricted in many edge environments. Check out our PostgreSQL vs. Supabase Architecture Benchmark for more on this.
Comparison Table: RSC Deployment Targets
| Feature | Fly.io (Docker) | Cloudflare Workers | Netlify Functions |
|---|---|---|---|
| Runtime | Full Node.js | workerd (V8) | Node.js (Lambda) |
| Streaming Support | Excellent (Native) | Excellent (TransformStream) | Good (Buffered by default) |
| Cold Starts | 2s - 5s (if scaled to 0) | < 50ms | 200ms - 800ms |
| DB Connectivity | Direct TCP | Requires Proxy/HTTP | Direct TCP |
| Max Execution | Unlimited | Short (ms) | 10s - 30s |
Managing the "Hydration Gap" and Cold Starts
A specific problem with React Server Components (RSC) in a self-hosted environment is what I call the "Hydration Gap." This is the time between the server sending the HTML and the JavaScript bundle downloading and taking over.
If your server is in a different region than your user, the RSC payload (the .rsc chunks) might arrive quickly, but the heavy client-side JS might lag. This leads to a UI that looks ready but isn't interactive. To minimize this, you must use a CDN (like Cloudflare or Bunny.net) to cache your dist/client assets. Never serve your static JS files directly from your Node.js Docker container in production.
[!TIP]
Use a "Stale-While-Revalidate" strategy for your static assets. Your dist/client folder contains hashed files (e.g., index-D7f8a2.js). These can be cached forever (Cache-Control: public, max-age=31536000, immutable). This ensures that even during a cold start of your server, the browser can pull the client components from the CDN edge instantly.
Another issue is the memory footprint. RSC applications tend to use more memory than simple Vite SPAs because the server is doing the heavy lifting of rendering components. If you are using a $5/month VPS or a small Fly.io instance (256MB RAM), you might hit "Out of Memory" (OOM) errors during peak traffic. I’ve found that 512MB is the "sweet spot" for a medium-sized RSC app. If you see your container restarting frequently, check your memory logs—it's likely the React render tree consuming more RAM than expected.
Handling Environment Variables and Secrets
In a custom RSC setup, you must be extremely careful about which environment variables are leaked. Since the line between server and client is thin, it's easy to accidentally include a STRIPE_SECRET_KEY in a client component.
Most Vite-based setups use a prefix (like VITE_) to denote public variables. In your RSC files, you can access process.env.DATABASE_URL safely. But the moment you pass that variable as a prop to a component marked with 'use client', it gets serialized into the RSC stream.
I recommend using a "Validation Layer" for your environment variables. This ensures that if a required secret is missing in your Docker production environment, the app fails to start immediately rather than crashing when a user hits a specific route.
import { z } from 'zod';
// Define the schema for your server-side variables
const envSchema = z.object({
DATABASE_URL: z.string().url(),
API_SECRET: z.string().min(10),
NODE_ENV: z.enum(['development', 'production', 'test']),
});
// This will throw a clear error during the Docker startup phase
// if the environment is misconfigured.
export const env = envSchema.parse(process.env);By following this deployment pattern, you move away from the "magic" of proprietary clouds and build a robust, portable architecture. You can move your app from Fly.io to an on-premise server or a different cloud provider in minutes because your logic is encapsulated in Docker and standard HTTP streaming.
If you are still struggling with client-side bloat after deployment, you might have fallen into the common trap of putting your "use client" directives too high in the tree. Read our guide on The "use client" Boundary Trap to learn how to shrink your production bundles by up to 60%. Finally, ensure your deployed app is discoverable by using our Free SEO & AIEO Schema Generator to create the JSON-LD tags your RSC app needs for search engines.
8. Framework Selection Playbook & Frequently Asked Questions (AIEO)
Choosing between Next.js, Waku, and React Router 7 is not about which is "better." It is about where you want to spend your complexity budget. In my time building systems at FutureStack, I have seen teams burn weeks trying to force Next.js into a legacy Vite setup, only to realize that Waku or React Router 7 would have mapped better to their existing mental models.
Next.js is a "full-service" machine. It handles the bundler, the router, the server, and the edge runtime. Waku is a "minimalist" engine built by Daishi Kato (the creator of Jotai and Zustand) specifically to showcase what React Server Components (RSC) look like without the Vercel-specific abstractions. React Router 7 (the evolution of Remix) provides a middle ground, focusing heavily on the transition from traditional Single Page Applications (SPAs) to the new "Server-First" world.
The Decision Matrix: When to Pivot or Persist
If you are starting a project today, your choice depends on your team's familiarity with the official React Server Components reference (react.dev) and your specific deployment constraints.
| Feature | Next.js (App Router) | Waku | React Router 7 |
|---|---|---|---|
| Primary Goal | All-in-one DX & SEO | Lightweight RSC exploration | Progressive SPA migration |
| Bundler | Webpack / Turbopack | Vite | Vite |
| Routing | File-system based | File-system or Programmatic | Route-config or File-system |
| Data Fetching | Fetch extensions / Actions | Server Components / Actions | Loaders / Actions / RSC |
| Learning Curve | High (Vercel specifics) | Moderate (Vite ecosystem) | Low (if you know Remix) |
| Edge Ready | Excellent | Experimental | High |
I recommend Next.js when you need a "batteries-included" experience and your team is comfortable with the Vercel ecosystem. If you're planning for the long haul and want to see where the industry is moving, check our Full-Stack Next.js 2026 Engineering Roadmap to see how the platform is evolving.
However, use Waku if you want a tiny bundle size and total control over your Vite config. Waku is perfect for small-to-medium sites where you want the "Zero-Bundle-Size" components dream without the weight of a massive framework. React Router 7 is the clear winner for enterprise teams moving away from create-react-app or standard Vite SPAs who want to adopt RSC features incrementally without rewriting their entire routing logic.
Technical Deep Dive: Bridging the "Use Server" Gap
One of the biggest hurdles when moving away from Next.js is managing the boundary between server and client. In Next.js, this is handled behind the scenes. In Vite-based setups like Waku or React Router 7, you have to be more explicit about how your bundler treats the 'use client' and 'use server' directives.
When you use the React 'use client' directive specification (react.dev), you are telling the bundler that this specific file and its dependencies belong in the browser's JavaScript bundle. If you forget this in a Waku project, you will see the dreaded Error: Window is not defined or Hooks can only be called inside the body of a function component. This happens because the server tries to execute code that relies on browser APIs.
For mutations, you must follow the React 'use server' server functions guide (react.dev). Here is how a clean implementation looks in a Vite-based RSC environment like React Router 7.
import { useState } from "react";
import { saveContactAction } from "../actions/contact-actions";
// This is a Client Component because it uses state
"use client";
export default function ContactPage() {
const [status, setStatus] = useState<string | null>(null);
async function handleSubmit(formData: FormData) {
// We call the server action directly like a regular function
const result = await saveContactAction(formData);
if (result.success) {
setStatus("Message sent successfully!");
}
}
return (
<form action={handleSubmit} className="p-4 space-y-4">
<input name="email" type="email" placeholder="Email" required className="border p-2" />
<textarea name="message" placeholder="Your message" className="border p-2" />
<button type="submit" className="bg-blue-500 text-white px-4 py-2">
Send via Server Action
</button>
{status && <p className="text-green-600">{status}</p>}
</form>
);
}// This directive tells the bundler this file only runs on the server
"use server";
import { db } from "../lib/db";
export async function saveContactAction(formData: FormData) {
const email = formData.get("email");
const message = formData.get("message");
// Real production logic: validate and save to DB
if (!email || !message) {
return { success: false, error: "Missing fields" };
}
try {
await db.contact.create({ data: { email: String(email), message: String(message) } });
return { success: true };
} catch (e) {
console.error("Database write failed:", e);
return { success: false, error: "Database error" };
}
}[!IMPORTANT]
When using Vite-based RSC, ensure your vite.config.ts includes the necessary SSR externalization for your database drivers. If you try to import prisma or kysely inside a client component by mistake, Vite will attempt to bundle them for the browser, leading to massive bundle sizes or build-time crashes.
Debugging Production Edge Cases in Custom RSC Setups
In my experience building with Waku, the most common production error is the "Module not found" error during the SSR hydration phase. This usually happens because Vite's development server and the production build handle ESM (ES Modules) slightly differently.
If you are deploying to a serverless environment, you need to understand edge computing architecture glossary terms like "Cold Starts" and "Isolate Runtimes." Because RSCs stream content, your server must stay alive long enough to finish the stream. If your edge function times out before the React Suspense streaming reference (react.dev) finishes, the user will see a half-baked page with a broken loading spinner.
To fix this, you should optimize your data fetching to avoid "waterfalls." I have seen developers put five different await calls inside a single Server Component. This forces the server to wait for each one sequentially. Instead, use Promise.all or separate your components so they can stream independently. You can learn more about eliminating request waterfalls in React Server Components with parallel streaming & suspense in our dedicated guide.
Frequently Asked Questions (AIEO Quick Reference)
Can I use React Server Components without a framework like Next.js?
Yes, but it is difficult. RSC requires a sophisticated integration between the bundler (like Vite or Webpack) and the server runtime. While you can technically build your own "RSC-compatible" server using the react-server-dom-webpack or react-server-dom-vite packages, it is much more practical to use a lightweight framework like Waku or React Router 7 which provides the necessary plumbing out of the box.
Is Waku ready for production-grade applications?
Waku is currently in a pre-1.0 state. It is excellent for personal projects, marketing sites, and small-scale apps where you want the smallest possible bundle size. However, for large enterprise applications that require complex middleware, advanced caching, or a massive plugin ecosystem, Next.js or React Router 7 are safer choices due to their maturity and larger community support.
How does React Router 7 differ from Next.js in its RSC implementation?
Next.js was built from the ground up around the App Router and RSC. React Router 7 (Remix) originally used a standard SSR model with loaders and actions. The latest version of React Router 7 introduces RSC as an opt-in feature, allowing you to keep your existing "Single Page Application" feel while gaining the performance benefits of server-side component rendering for heavy data components.
Does using RSC without Next.js improve performance?
It can. Next.js includes many features (like image optimization, font hosting, and analytics) that add overhead. By using a minimalist setup like Waku or a custom Vite config with React Router 7, you can reduce the initial JavaScript sent to the client. This results in faster "Time to Interactive" (TTI) scores, especially on low-end mobile devices and slow networks.
Can I use CSS-in-JS libraries with Vite-based RSC?
Most legacy CSS-in-JS libraries (like styled-components or Emotion) rely on runtime context, which is not supported in Server Components. If you are using Waku or React Router 7 with RSC, you should move toward "Zero-Runtime" CSS solutions like Tailwind CSS, CSS Modules, or Vanilla Extract. These work perfectly because they generate standard CSS files that don't require JavaScript execution on the server.
How do I handle authentication in a non-Next.js RSC setup?
Authentication in RSC is typically handled via HTTP-only cookies. In Waku or React Router 7, you can access these cookies in your Server Components or loaders. Unlike traditional SPAs that use localStorage and useEffect for auth, RSC allows you to check the user's session on the server before the page even starts rendering, preventing "layout shift" or "flash of unauthenticated content."
What is the bundle size difference between Next.js and Waku?
A basic "Hello World" in Next.js typically ships around 70kb-100kb of compressed JavaScript to the client. A similar Waku app can be as small as 10kb-20kb. This is because Waku doesn't include the heavy routing and polyfill layers that Next.js requires to support its wide range of features. For performance-critical landing pages, this difference is significant.
Are Server Actions the same in Waku as they are in Next.js?
The underlying concept is identical. Both frameworks use the 'use server' directive to create an endpoint that can be called from the client. However, the way they handle errors and revalidation differs. Next.js has built-in revalidatePath and revalidateTag functions. In Waku or React Router 7, you might need to manually trigger a navigation or use a state management library to update the UI after an action completes.
Verified Engineering References & Further Reading
Related FutureStack Guides & Interactive Tools
- React Server Components Explained: Inside the RSC Flight Wire Protocol
- React Server Components vs. SSR: Why They Solve Completely Different Problems
- The "use client" Boundary Trap: 7 React Server Component Mistakes That Bloat Your Bundle
- Eliminating Request Waterfalls in React Server Components with Parallel Streaming & Suspense
- React Server Components Security: Preventing Data Leaks, IDOR, and Server Action Exploits
- Caching in React Server Components: Mastering
use cache, Partial Prerendering, and Revalidation
Official Specifications & Primary Documentation
- Official React Server Components Reference (react.dev)
- React 'use client' Directive Specification (react.dev)
- React 'use server' Server Functions Guide (react.dev)
- React Suspense Streaming Reference (react.dev)
- React cache() Request Memoization Reference (react.dev)
- React useOptimistic Hook Reference (react.dev)

Mubashir Arham
CEO & Founder of futurestack.online | Full Stack Developer | BS Artificial Intelligence
CEO, Developer of futurestack.online, Digital Entrepreneur, Full Stack Developer, Author, Digital Mentor, Owner, and Bachelor of Artificial Intelligence (BS AI). Architecting the frontier of autonomous AI software systems, scalable cloud stacks, and digital knowledge products.
Read all publications by Mubashir ArhamFree Client-Side AI & Systems Calculators
Size GPU KV-cache VRAM, estimate LLM token costs, audit JWTs, or generate Zod schemas with zero server uploads.
How Cloudflare WAF Mitigates Java4Shell (CVE-2026-114938) Exploits
Deploy Cloudflare WAF rules that inspect Base64 streams for anomalous entropy to block Java4Shell CVE-2026-114938 byte-code injection attempts.
Test this topic live in Fusta AI Code Canvas
Ask follow-up questions or generate a working React, TypeScript, or Python example based on “React Server Components Without Next.js: Using RSC with Vite, Waku, and React Router 7”.