├── .eslintrc.cjs ├── .gitignore ├── .tool-versions ├── LICENSE ├── README.md ├── bun.lockb ├── package.json ├── src ├── Object.ts ├── Runtime.ts ├── RuntimeBrowser.ts ├── RuntimeNode.ts ├── ServerComponent.tsx ├── ServerComponentContext.tsx ├── Uint8ArraySink.ts ├── index.ts └── react-server-dom-webpack.d.ts └── tsconfig.json /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: [ 3 | "eslint:recommended", 4 | "plugin:@typescript-eslint/recommended", 5 | "plugin:require-extensions/recommended", 6 | ], 7 | parser: "@typescript-eslint/parser", 8 | parserOptions: { 9 | EXPERIMENTAL_useProjectService: true, 10 | project: true, 11 | tsconfigRootDir: __dirname, 12 | }, 13 | plugins: ["@typescript-eslint", "require-extensions"], 14 | root: true, 15 | rules: { 16 | "@typescript-eslint/no-namespace": "off", 17 | "@typescript-eslint/no-unused-vars": [ 18 | "warn", 19 | { 20 | argsIgnorePattern: "^_", 21 | varsIgnorePattern: "^_", 22 | caughtErrorsIgnorePattern: "^_", 23 | }, 24 | ], 25 | }, 26 | }; 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | node_modules -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | bun 1.1.12 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Daniel Nagy 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Distributed Components 2 | 3 | Effortlessly compose client and server components. 4 | 5 | ## Introduction 6 | 7 | The goal of this library is to enable rendering server components declaratively from client components, using familiar component composition, and in a way that is router-agnostic. 8 | 9 | > [!NOTE] 10 | > This package currently depends on the **react-server-dom-webpack** package. You must provide a manifest that is compatible with that package. If you're using Webpack, then you can use the Webpack plugin. If you are not using Webpack, then you probably want to wait for these APIs to mature and not be dependent on a specific module bundler. 11 | 12 | React allows composing client and server components, but only if the current component is a server component. In other words, you cannot render a server component in a client component. In addition, if you pass a server component as a prop to a client component, then React will eagerly render that component. React must render the server component in case the client component is mounted. However, there is no guarantee that the client component will be mounted. 13 | 14 | Consider the following example: 15 | 16 | ```jsx 17 | const ServerRoutes = () => ( 18 | 19 | } /> 20 | } /> 21 | 22 | ); 23 | ``` 24 | 25 | If the `` component is a client component and the `` and `` components are server components, then both the `` and `` components will be rendered on the server. React will skip rendering the `` component because it is a client component and eagerly render the `` and `` components because they are passed as props to the client component. 26 | 27 | Furthermore, server components are inert. They render once on the server and only on the server, and they do not react to state changes. Because of this, Meta-frameworks have decided to tightly couple server components to a router. However, it is not strictly necessary to couple server components to a router. It is possible to devise an API for rerendering server components when their props change on the client. 28 | 29 | This library attempts to solve these issues; specifically, it allows you to: 30 | 31 | - Render server components declaratively in client components. 32 | - Render server components only when they are mounted. 33 | - Rerender server components when their props change on the client. 34 | - Cache server components on the client so that they may be unmounted and remounted without a round trip to the server. 35 | 36 | I believe that this may provide a path for incremental adoption of server components, where it makes sense, for existing React apps. 37 | 38 | ## Getting Started 39 | 40 | To get started, install the package from the npm registry. 41 | 42 | ``` 43 | npm add react-distributed-components 44 | ``` 45 | 46 | > [!WARNING] 47 | > This package is experimental. I provide no warranties. Use at your own risk, and expect breaking changes. 48 | 49 | To render a server component from a client component, use a ``. For example: 50 | 51 | ```tsx 52 | import { ServerComponent } from "react-distributed-components"; 53 | 54 | type HomePage = (typeof import("./HomePage.js"))["HomePage"]; 55 | 56 | const HomePage = () => ( 57 | 58 | suspense={{ fallback: "loading home page" }} 59 | type="HomePage" 60 | /> 61 | ); 62 | ``` 63 | 64 | In this example, I have created a `` client component that acts as a proxy to the `` server component. When the `` client component is mounted, it will make a request to the server to render the `` server component. 65 | 66 | In order to know which endpoint to call and how to render the RSC payload, some additional context is required. 67 | 68 | ```tsx 69 | import { 70 | ServerComponent, 71 | ServerComponentContext, 72 | } from "react-distributed-components"; 73 | 74 | import ssrManifest from "./ssrManifest.json" with { type: "json" }; 75 | import { callServer } from "./callServer.js"; 76 | 77 | type HomePage = (typeof import("./HomePage.js"))["HomePage"]; 78 | 79 | const HomePage = () => ( 80 | 81 | suspense={{ fallback: "loading home page" }} 82 | type="HomePage" 83 | /> 84 | ); 85 | 86 | const App: FC<{ url: string }> = ({ url }) => { 87 | const { origin } = new URL(url); 88 | 89 | return ( 90 | 97 | 98 | 99 | ); 100 | }; 101 | ``` 102 | 103 | This package currently depends on the **react-server-dom-webpack** package. You must implement the `CallServerCallback` and provide a manifest that is compatible with that package. 104 | 105 | Finally, the `/render` HTTP endpoint needs to be implemented to render the server component. Here is an example using Hono: 106 | 107 | ```ts 108 | import { type Context, type Next, Hono } from "hono"; 109 | import { PassThrough, Readable } from "node:stream"; 110 | import { 111 | decodeReply, 112 | renderToPipeableStream, 113 | } from "react-server-dom-webpack/server"; 114 | 115 | import clientManifest from "./clientManifest.json" with { type: "json" }; 116 | import { HomePage } from "./HomePage.js"; 117 | 118 | app.post("/render", renderServerComponent); 119 | 120 | async function renderServerComponent(context: Context, _next: Next) { 121 | type Body = 122 | | { type: "HomePage"; props: HomePage.Props }; 123 | 124 | const body = await decodeReply(await context.req.text()); 125 | const { type, props } = body; 126 | 127 | const Component = () => { 128 | switch (type) { 129 | case "HomePage": 130 | return ; 131 | } 132 | }; 133 | 134 | const { pipe } = renderToPipeableStream(, manifest); 135 | const rscPayload = pipe(new PassThrough()); 136 | 137 | return context.newResponse(Readable.toWeb(rscPayload) as ReadableStream); 138 | } 139 | ``` 140 | 141 | The client component is going to make a `POST` request to the server. The body of the request will contain the component type and props. The endpoint is expected to respond with the RSC payload. 142 | 143 | ## API 144 | 145 | ### ServerComponent 146 | 147 | _Client Component_ 148 | 149 | ```ts 150 | type ServerComponent = >(props: { 151 | /** 152 | * Props to be forwarded to the server component. 153 | */ 154 | props?: ComponentProps; 155 | /** 156 | * Optionally provide a fallback while the server component is loading. 157 | */ 158 | suspense?: SuspenseProps; 159 | /** 160 | * Identifies the type of the server component. The server will use this value 161 | * to know which server component to render. 162 | */ 163 | type: string; 164 | }) => ReactNode; 165 | ``` 166 | 167 | A `ServerComponent` is a client component that acts as a proxy for a server component. 168 | 169 | #### Example 170 | 171 | ```tsx 172 | import { ServerComponent } from "react-distributed-components"; 173 | 174 | type HomePage = (typeof import("./HomePage.js"))["HomePage"]; 175 | 176 | const HomePage = () => ( 177 | 178 | suspense={{ fallback: "loading home page" }} 179 | type="HomePage" 180 | /> 181 | ); 182 | ``` 183 | 184 | ### Context 185 | 186 | _Type_ 187 | 188 | ```ts 189 | type Context = { 190 | /** 191 | * An in-memory RSC payload cache keyed by component props. 192 | */ 193 | cache: Map; 194 | /** 195 | * Forwarded to react-server-dom-webpack. 196 | */ 197 | callServer?: CallServerCallback; 198 | /** 199 | * The endpoint that renders the server component. The type and props will be 200 | * in the POST body. 201 | */ 202 | endpoint: string; 203 | /** 204 | * Forwarded to react-server-dom-webpack. 205 | */ 206 | ssrManifest?: SSRManifest; 207 | }; 208 | ``` 209 | 210 | A `ServerComponent` requires context to know which endpoint to call and how to render the RSC payload. 211 | 212 | ### ServerComponentContext 213 | 214 | _Client Component_ 215 | 216 | ```ts 217 | type ServerComponentContext = React.Provider; 218 | ``` 219 | 220 | A `ServerComponentContext` is used to provide context to a `ServerComponent`. 221 | 222 | #### Example 223 | 224 | ```tsx 225 | import { ServerComponentContext } from "react-distributed-components"; 226 | 227 | import ssrManifest from "./ssrManifest.json" with { type: "json" }; 228 | import { callServer } from "./callServer.js"; 229 | 230 | const App: FC<{ url: string }> = ({ url }) => { 231 | const { origin } = new URL(url); 232 | 233 | return ( 234 | 242 | {/* children */} 243 | 244 | ); 245 | }; 246 | ``` 247 | -------------------------------------------------------------------------------- /bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/daniel-nagy/react-distributed-components/ec7d820271854ee5f02ac004e0ab7475df4577fe/bun.lockb -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-distributed-components", 3 | "type": "module", 4 | "version": "0.2.0", 5 | "description": "Effortlessly compose client and server components.", 6 | "author": "Daniel Nagy <1622446+daniel-nagy@users.noreply.github.com>", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/daniel-nagy/react-distributed-components.git" 10 | }, 11 | "files": [ 12 | "build", 13 | "!.tsinfo" 14 | ], 15 | "exports": { 16 | ".": "./build/index.js" 17 | }, 18 | "imports": { 19 | "#Runtime.js": { 20 | "node": "./build/RuntimeNode.js", 21 | "default": "./build/RuntimeBrowser.js" 22 | } 23 | }, 24 | "publishConfig": { 25 | "access": "public", 26 | "registry": "https://registry.npmjs.org" 27 | }, 28 | "scripts": { 29 | "build": "tsc -p tsconfig.json", 30 | "clean": "rm -rf build", 31 | "eslint": "eslint src", 32 | "eslint:fix": "eslint src --fix", 33 | "prebuild": "yarn clean", 34 | "prepack": "yarn build", 35 | "prettier": "prettier --check --ignore-path .gitignore .", 36 | "prettier:fix": "prettier --write --ignore-path .gitignore ." 37 | }, 38 | "dependencies": {}, 39 | "peerDependencies": { 40 | "react": "*", 41 | "react-server-dom-webpack": "*" 42 | }, 43 | "devDependencies": { 44 | "@types/node": "^20.13.0", 45 | "@types/react": "npm:types-react@beta", 46 | "@types/react-dom": "npm:types-react-dom@beta", 47 | "@typescript-eslint/eslint-plugin": "^7.11.0", 48 | "@typescript-eslint/parser": "^7.11.0", 49 | "eslint": "^8.57.0", 50 | "eslint-plugin-require-extensions": "^0.1.3", 51 | "prettier": "^3.3.0", 52 | "react": "^19.0.0-rc-6d3110b4d9-20240531", 53 | "react-dom": "^19.0.0-rc-6d3110b4d9-20240531", 54 | "react-server-dom-webpack": "19.0.0-rc-6d3110b4d9-20240531", 55 | "typescript": "^5.4.5" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Object.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Drops any optional keys from an object. A key is considered optional if its 3 | * value may be `undefined` (even if the key is required). 4 | */ 5 | export type TakeRequired = { 6 | [K in keyof T as undefined extends T[K] ? never : K]: T[K]; 7 | }; 8 | 9 | /** 10 | * Produces the type `true` if the object has no keys. Otherwise it produces the 11 | * type `false`. 12 | */ 13 | export type IsEmpty = keyof T extends never ? true : false; 14 | 15 | /** 16 | * Produces the type `true` if the object has at least one required key. A key 17 | * is considered optional if its value may be `undefined`. Otherwise it produces 18 | * the type `false`. 19 | */ 20 | export type HasRequiredKeys = 21 | IsEmpty> extends true ? false : true; 22 | -------------------------------------------------------------------------------- /src/Runtime.ts: -------------------------------------------------------------------------------- 1 | import type { ReactNode, Thenable } from "react"; 2 | import type { Options as BrowserOptions } from "react-server-dom-webpack/client.browser"; 3 | import type { 4 | Options as NodeOptions, 5 | SSRManifest, 6 | } from "react-server-dom-webpack/client.node"; 7 | 8 | /* 9 | * The `Runtime` protocol must be implemented for each supported runtime. 10 | */ 11 | 12 | export type Options = (BrowserOptions & NodeOptions) & { 13 | ssrManifest?: SSRManifest; 14 | }; 15 | 16 | /** 17 | * Reads the RSC payload from the document so that the component can be hydrated 18 | * on the client without refetching the RSC payload from the server. 19 | */ 20 | export type getRscPayloadFromDocument = ( 21 | key: string 22 | ) => ReadableStream | null; 23 | 24 | /** 25 | * Transforms the RSC payload into React nodes that can be rendered on the 26 | * client. 27 | */ 28 | export type render = ( 29 | rscPayload: ReadableStream, 30 | options?: Options 31 | ) => Thenable; 32 | -------------------------------------------------------------------------------- /src/RuntimeBrowser.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import type { ReactNode } from "react"; 4 | import { createFromReadableStream } from "react-server-dom-webpack/client.browser"; 5 | 6 | import type * as Runtime from "./Runtime.js"; 7 | 8 | /** 9 | * Reads the RSC payload from the document so that the component can be hydrated 10 | * on the client without refetching the RSC payload from the server. 11 | */ 12 | export const getRscPayloadFromDocument: Runtime.getRscPayloadFromDocument = ( 13 | key 14 | ) => { 15 | const data = JSON.parse(document.getElementById(key)?.textContent ?? "null"); 16 | return data && new Response(new Uint8Array(data)).body; 17 | }; 18 | 19 | /** 20 | * Transforms the RSC payload into React nodes that can be rendered on the 21 | * client. 22 | */ 23 | export const render: Runtime.render = (rscPayload, options) => { 24 | return createFromReadableStream(rscPayload, options); 25 | }; 26 | -------------------------------------------------------------------------------- /src/RuntimeNode.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | import { Readable } from "node:stream"; 4 | import type { ReadableStream } from "node:stream/web"; 5 | import type { ReactNode } from "react"; 6 | import { createFromNodeStream } from "react-server-dom-webpack/client.node"; 7 | 8 | import type * as Runtime from "./Runtime.js"; 9 | 10 | /** 11 | * This is a noop since the component cannot be hydrated in a Node runtime. 12 | */ 13 | export const getRscPayloadFromDocument: Runtime.getRscPayloadFromDocument = ( 14 | _key 15 | ) => null; 16 | 17 | /** 18 | * Transforms the RSC payload into React nodes that can be rendered on the 19 | * client. 20 | */ 21 | export const render: Runtime.render = ( 22 | rscPayload, 23 | { ssrManifest, ...options } = {} 24 | ) => { 25 | return createFromNodeStream( 26 | Readable.fromWeb(rscPayload as ReadableStream), 27 | ssrManifest!, 28 | options 29 | ); 30 | }; 31 | -------------------------------------------------------------------------------- /src/ServerComponent.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { 4 | type ComponentProps, 5 | type ComponentType, 6 | type FC, 7 | type ReactNode, 8 | type SuspenseProps as ReactSuspenseProps, 9 | Suspense, 10 | startTransition, 11 | use, 12 | useEffect, 13 | useRef, 14 | useState, 15 | } from "react"; 16 | import { encodeReply } from "react-server-dom-webpack/client.browser"; 17 | 18 | import { getRscPayloadFromDocument, render } from "#Runtime.js"; 19 | import type { HasRequiredKeys } from "./Object.js"; 20 | import { useServerComponentContext } from "./ServerComponentContext.js"; 21 | import { Uint8ArraySink } from "./Uint8ArraySink.js"; 22 | 23 | type SuspenseProps = Omit; 24 | 25 | export namespace ServerComponent { 26 | type WithComponentProps = 27 | HasRequiredKeys> extends true 28 | ? { 29 | /** 30 | * Props to be forwarded to the server component. 31 | */ 32 | props: ComponentProps; 33 | } 34 | : { props?: ComponentProps }; 35 | 36 | export type Props = WithComponentProps & { 37 | /** 38 | * Optionally provide a fallback while the server component is loading. 39 | */ 40 | suspense?: SuspenseProps; 41 | /** 42 | * Identifies the type of the server component. The server will use this value 43 | * to know which server component to render. 44 | */ 45 | type: string; 46 | }; 47 | } 48 | 49 | /** 50 | * Renders a server component on the client. An HTTP POST request will be made 51 | * to the configured endpoint whenever the component's props change. 52 | * 53 | * The payload sent to the server will contain the `type` and `props` passed to 54 | * this component. The server must render the component and respond with the RSC 55 | * payload. 56 | * 57 | * The RSC payload will be cached in memory on the client. The cache is keyed 58 | * by the props. This prevents rerendering the server component if it is 59 | * unmounted and remounted. This enables immediate navigation to a previously 60 | * rendered server component without rerendering it on the server. 61 | * 62 | * This component uses React's Suspense API. You may provide a suspense fallback 63 | * to display a loading state while the component is rendering. 64 | */ 65 | export const ServerComponent = 66 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 67 | >({ 68 | props, 69 | suspense, 70 | type, 71 | }: ServerComponent.Props): ReactNode => { 72 | const { cache, callServer, endpoint, ssrManifest } = 73 | useServerComponentContext(); 74 | 75 | const getRscPayloadFromCache = ( 76 | key: string 77 | ): ReadableStream | null => { 78 | return cache.has(key) ? new Response(cache.get(key)).body : null; 79 | }; 80 | 81 | const getPromise = async (type: string, props?: ComponentProps) => { 82 | const body = (await encodeReply({ type, props })) as string; 83 | const key = body; 84 | let responseBody: ReadableStream | null | undefined; 85 | 86 | responseBody = getRscPayloadFromCache(key); 87 | responseBody ??= getRscPayloadFromDocument(key); 88 | responseBody ??= (await fetch(endpoint, { body, method: "POST" })).body!; 89 | 90 | const [left, right] = responseBody.tee(); 91 | const sink = new Uint8ArraySink(); 92 | 93 | left.pipeTo(sink); 94 | 95 | const content = await render(right, { callServer, ssrManifest }); 96 | cache.set(body, sink.data); 97 | 98 | return { 99 | content, 100 | key, 101 | rscPayload: sink.data, 102 | }; 103 | }; 104 | 105 | const [promise, setPromise] = useState(() => getPromise(type, props)); 106 | const didMount = useRef(false); 107 | 108 | useEffect(() => { 109 | if (!didMount.current) return void (didMount.current = true); 110 | 111 | startTransition(() => { 112 | setPromise(getPromise(type, props)); 113 | }); 114 | }, [type, props]); 115 | 116 | return ( 117 | 118 | 119 | 120 | ); 121 | }; 122 | 123 | const Async: FC<{ 124 | promise: Promise<{ 125 | content: ReactNode; 126 | key: string; 127 | rscPayload: Uint8Array; 128 | }>; 129 | }> = ({ promise }) => { 130 | const { content, key, rscPayload } = use(promise); 131 | 132 | return ( 133 | <> 134 | {content} 135 | 138 | 139 | ); 140 | }; 141 | -------------------------------------------------------------------------------- /src/ServerComponentContext.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { createContext, use } from "react"; 4 | import type { CallServerCallback } from "react-server-dom-webpack/client.browser"; 5 | import type { SSRManifest } from "react-server-dom-webpack/client.node"; 6 | 7 | export type Context = { 8 | /** 9 | * An in-memory RSC payload cache keyed by component props. 10 | */ 11 | cache: Map; 12 | /** 13 | * Forwarded to react-server-dom-webpack. 14 | */ 15 | callServer?: CallServerCallback; 16 | /** 17 | * The endpoint that renders the server component. The type and props will be 18 | * in the POST body. 19 | */ 20 | endpoint: string; 21 | /** 22 | * Forwarded to react-server-dom-webpack. 23 | */ 24 | ssrManifest?: SSRManifest; 25 | }; 26 | 27 | const ServerComponentContext = createContext({ 28 | cache: new Map(), 29 | endpoint: "", 30 | }); 31 | 32 | /* 33 | * A wrapper around ServerComponentContext.Provider. This is necessary to make 34 | * it a client component. Otherwise, rendering it in a server component will 35 | * error. 36 | */ 37 | const Provider = (({ value, ...props }) => { 38 | const parentContext = useServerComponentContext(); 39 | 40 | return ( 41 | 45 | ); 46 | }) as typeof ServerComponentContext.Provider; 47 | 48 | export { Provider as ServerComponentContext }; 49 | 50 | export const useServerComponentContext = () => use(ServerComponentContext); 51 | -------------------------------------------------------------------------------- /src/Uint8ArraySink.ts: -------------------------------------------------------------------------------- 1 | export class Uint8ArraySink extends WritableStream { 2 | data: Uint8Array = new Uint8Array(); 3 | 4 | constructor(options?: Omit, "write">) { 5 | super({ 6 | ...options, 7 | write: (chunk) => { 8 | this.data = new Uint8Array([...this.data, ...chunk]); 9 | }, 10 | }); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./ServerComponent.js"; 2 | export { 3 | type Context, 4 | ServerComponentContext, 5 | } from "./ServerComponentContext.js"; 6 | -------------------------------------------------------------------------------- /src/react-server-dom-webpack.d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-explicit-any */ 2 | // Crude types for react-server-dom-webpack since none are currently published. 3 | 4 | declare module "shared/ReactTypes" { 5 | export type ReactCustomFormAction = { 6 | name?: string; 7 | action?: string; 8 | encType?: string; 9 | method?: string; 10 | target?: string; 11 | data?: null | FormData; 12 | }; 13 | } 14 | 15 | declare module "react-client" { 16 | type ReactServerObject = { [key: string]: ReactServerValue }; 17 | 18 | export type ReactServerValue = 19 | // References are passed by their value 20 | | ServerReference 21 | // The rest are passed as is. Sub-types can be passed in but lose their 22 | // subtype, so the receiver can only accept once of these. 23 | | string 24 | | boolean 25 | | number 26 | | null 27 | | void 28 | | bigint 29 | | AsyncIterable 30 | | AsyncIterator 31 | | Iterable 32 | | Iterator 33 | | Array 34 | | Map 35 | | Set 36 | | FormData 37 | | Date 38 | | ReactServerObject 39 | | Promise; // Thenable 40 | 41 | interface Reference {} 42 | export type ServerReference = T; 43 | export type TemporaryReferenceSet = Map; 44 | } 45 | 46 | declare module "react-server" { 47 | export type ClientReference = unknown; 48 | export type ServerReference = unknown; 49 | export type React$Element = unknown; 50 | export type LazyComponent = unknown; 51 | export type React$AbstractComponent = unknown; 52 | 53 | // Serializable values 54 | export type ReactClientValue = 55 | // Server Elements and Lazy Components are unwrapped on the Server 56 | | React$Element> 57 | | LazyComponent 58 | // References are passed by their value 59 | | ClientReference 60 | | ServerReference 61 | // The rest are passed as is. Sub-types can be passed in but lose their 62 | // subtype, so the receiver can only accept once of these. 63 | | React$Element 64 | | React$Element & any> 65 | | string 66 | | boolean 67 | | number 68 | | symbol 69 | | null 70 | | void 71 | | bigint 72 | | ReadableStream 73 | | AsyncIterable 74 | | AsyncIterator 75 | | Iterable 76 | | Iterator 77 | | Array 78 | | Map 79 | | Set 80 | | FormData 81 | | ArrayBufferView 82 | | ArrayBuffer 83 | | Date 84 | | ReactClientObject 85 | | Promise; // Thenable 86 | 87 | type ReactClientObject = { [key: string]: ReactClientValue }; 88 | } 89 | 90 | declare module "react-server-dom-webpack/client.browser" { 91 | import type { Thenable } from "react"; 92 | import type { TemporaryReferenceSet } from "react-client"; 93 | 94 | type CallServerCallback = (string, args: A) => Promise; 95 | 96 | type Options = { 97 | callServer?: CallServerCallback; 98 | temporaryReferences?: TemporaryReferenceSet; 99 | }; 100 | 101 | export function createFromFetch( 102 | promiseForResponse: Promise, 103 | options?: Options 104 | ): Thenable; 105 | 106 | export function createFromReadableStream( 107 | stream: ReadableStream, 108 | options?: Options 109 | ): Thenable; 110 | 111 | export function encodeReply( 112 | value: ReactServerValue, 113 | options?: { temporaryReferences?: TemporaryReferenceSet } 114 | ): Promise; 115 | } 116 | 117 | declare module "react-server-dom-webpack/client.node" { 118 | import type { Readable } from "node:stream"; 119 | import type { Thenable } from "react"; 120 | import type { ReactCustomFormAction } from "shared/ReactTypes"; 121 | 122 | type ClientReference = { 123 | specifier: string; 124 | name: string; 125 | async?: boolean; 126 | }; 127 | 128 | type SSRModuleMap = { 129 | [clientId: string]: { 130 | [clientExportName: string]: ClientReference; 131 | }; 132 | }; 133 | 134 | type ModuleLoading = null | { 135 | prefix: string; 136 | crossOrigin?: "use-credentials" | ""; 137 | }; 138 | 139 | type EncodeFormActionCallback = ( 140 | id: any, 141 | args: Promise 142 | ) => ReactCustomFormAction; 143 | 144 | type SSRManifest = { 145 | moduleMap: SSRModuleMap; 146 | moduleLoading: ModuleLoading; 147 | }; 148 | 149 | export type Options = { 150 | nonce?: string; 151 | encodeFormAction?: EncodeFormActionCallback; 152 | }; 153 | 154 | export function createFromNodeStream( 155 | stream: Readable, 156 | ssrManifest: SSRManifest, 157 | options?: Options 158 | ): Thenable; 159 | } 160 | 161 | declare module "react-server-dom-webpack/node-loader" { 162 | import type { LoadHook, ResolveHook } from "node:module"; 163 | export const load: LoadHook; 164 | export const resolve: ResolveHook; 165 | } 166 | 167 | declare module "react-server-dom-webpack/server" { 168 | import type { Thenable } from "react"; 169 | import type { TemporaryReferenceSet } from "react-client"; 170 | import type { ReactClientValue } from "react-server"; 171 | 172 | export type ImportManifestEntry = { 173 | id: string; 174 | // chunks is a double indexed array of chunkId / chunkFilename pairs 175 | chunks: Array; 176 | name: string; 177 | }; 178 | 179 | type ServerManifest = void; 180 | type ClientReferenceManifestEntry = ImportManifestEntry; 181 | 182 | type Options = { 183 | environmentName?: string; 184 | onError?: (error: mixed) => void; 185 | onPostpone?: (reason: string) => void; 186 | identifierPrefix?: string; 187 | temporaryReferences?: TemporaryReferenceSet; 188 | }; 189 | 190 | export type ClientManifest = { 191 | [id: string]: ClientReferenceManifestEntry; 192 | }; 193 | 194 | export function decodeReply( 195 | body: string | FormData, 196 | webpackMap: ServerManifest, 197 | options?: { temporaryReferences?: TemporaryReferenceSet } 198 | ): Thenable; 199 | 200 | export function renderToPipeableStream( 201 | model: ReactClientValue, 202 | webpackMap: ClientManifest, 203 | options?: Options 204 | ): PipeableStream; 205 | } 206 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": false, 4 | "allowSyntheticDefaultImports": true, 5 | "declaration": true, 6 | "esModuleInterop": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "incremental": true, 9 | "isolatedModules": true, 10 | "jsx": "react-jsx", 11 | "lib": ["ES2022"], 12 | "module": "ESNext", 13 | "moduleResolution": "Bundler", 14 | "noUncheckedIndexedAccess": true, 15 | "outDir": "build", 16 | "resolveJsonModule": true, 17 | "rootDir": "./src", 18 | "skipLibCheck": true, 19 | "strict": true, 20 | "target": "ES2018", 21 | "tsBuildInfoFile": "build/.tsinfo", 22 | "types": [], 23 | "useDefineForClassFields": true 24 | }, 25 | "exclude": [], 26 | "include": ["src"] 27 | } 28 | --------------------------------------------------------------------------------