Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created August 20, 2024 11:42
Show Gist options
  • Save sibelius/00440c0f68af5d5de7a1a55ad26b29d5 to your computer and use it in GitHub Desktop.
Save sibelius/00440c0f68af5d5de7a1a55ad26b29d5 to your computer and use it in GitHub Desktop.
renderToPipeableStreamPromise
export const renderToPipeableStreamPromise = async (
tree: ReactElement,
ctx: Context,
next: Next,
) => {
const writableStream = new WritableAsPromise();
let didError = false;
const { pipe, abort } = renderToPipeableStream(tree, {
onError(error) {
writableStream._destroy(error);
abort();
ctx.status = 500;
// eslint-disable-next-line no-console
console.error(error);
},
onShellReady() {
ctx.status = didError ? 500 : 200;
ctx.set('Content-Type', 'text/html');
writableStream._write(ctx.body ?? '', undefined, next);
pipe(writableStream);
},
onShellError(error) {
writableStream._destroy(error, next);
abort();
didError = true;
ctx.set('Content-Type', 'text/html');
ctx.body = '<!doctype html><p>Loading...</p><script src="clientrender.js"></script>';
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment