Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/app/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type React from 'react';
import { useEffect } from 'react';
import { lazy, Suspense, useEffect } from 'react';

const Title = lazy(() => import('./components/title.js').then((module) => ({ default: module.Title })));

export interface AppProps {
text: string;
Expand All @@ -10,5 +12,9 @@ export const App: React.FC<AppProps> = ({ text }) => {
console.log('hello from client!');
}, []);

return <h1>{text}</h1>;
return (
<Suspense fallback="loading...">
<Title>{text}</Title>
</Suspense>
);
};
5 changes: 5 additions & 0 deletions packages/app/src/components/title.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { FC } from 'react';

export const Title: FC<{ children: string }> = ({ children }) => {
return <h1>{children}</h1>;
};
62 changes: 31 additions & 31 deletions packages/server/src/render.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import ReactDOMServer from 'react-dom/server';
import { App } from 'app';
import { on } from 'events';
import type { Express, Request, Response } from 'express';
import fs from 'fs';
import { htmlPath } from './consts.js';
Expand All @@ -22,16 +21,7 @@ async function render(_request: Request, response: Response) {
'x-content-type-options': 'nosniff',
});

const html = await fs.promises.readFile(htmlPath, 'utf8');

for await (const { chunk, shouldFlush } of renderChunks(html)) {
response.write(chunk);
if (shouldFlush) {
response.flush();
}
}

return response.end();
return renderChunks(response);
} catch (error) {
console.error(error);
return response.status(500).send(error instanceof Error ? error.message : error);
Expand All @@ -57,30 +47,40 @@ function injectScripts(html: string) {
return html;
}

async function* renderChunks(html: string): AsyncGenerator<{ chunk: string; shouldFlush: boolean }> {
const abortController = new AbortController();
async function renderChunks(response: Response) {
const initialHtml = await fs.promises.readFile(htmlPath, 'utf8');
const html = injectScripts(initialHtml);

html = injectScripts(html);
let didError = false;

const stream = ReactDOMServer.renderToStaticNodeStream(<App text="Hello World (hydrated)" />);
const [start, end, openDiv] = [...html.split('<div id="root">'), '<div id="root" data-ssr>'];
const [start, _end, openDiv] = [...html.split('<div id="root">'), '<div id="root" data-ssr>'];

yield { chunk: start, shouldFlush: false };
yield { chunk: openDiv, shouldFlush: true };
const stream = ReactDOMServer.renderToPipeableStream(<App text="Hello World (hydrated)" />, {
onShellReady() {
response.statusCode = didError ? 500 : 200;

stream.on('end', () => {
abortController.abort('Finished rendering');
});
response.write(start);
response.write(openDiv);

try {
for await (const chunk of on(stream, 'data', { signal: abortController.signal })) {
yield { chunk: String(chunk), shouldFlush: false };
}
} catch (errorOrAbort) {
if (!abortController.signal.aborted) {
throw errorOrAbort; // It's an error.
}
}
stream.pipe(response);

yield { chunk: end, shouldFlush: true };
// Missing closing part of the div tag.
},
onShellError(error) {
response.statusCode = 500;
response.send(
initialHtml.replace(
'</body>',
`<script>console.error('SSR Error - Fallback to client render', JSON.stringify('${String(
error
)}'))</script></body>`
)
);
},
onError(error) {
didError = true;
response.statusCode = 500;
console.error(error);
},
});
}