Skip to content

Commit

Permalink
use solution from remix-run/remix#4822 (comment)
Browse files Browse the repository at this point in the history
  • Loading branch information
phollome committed Dec 15, 2022
1 parent 49bc23c commit 7b1c10b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 8 deletions.
48 changes: 40 additions & 8 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { renderToString } from "react-dom/server";
import { PassThrough } from "stream";
import type { EntryContext } from "@remix-run/node";
import { Response } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import isbot from "isbot";
import { renderToPipeableStream } from "react-dom/server";

declare global {
namespace NodeJS {
Expand Down Expand Up @@ -43,20 +46,49 @@ if (process.env.IMGPROXY_SALT === undefined) {
throw new Error("'IMGPROXY_SALT' is required");
}

const ABORT_DELAY = 5000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
const markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
const callbackName = isbot(request.headers.get("user-agent"))
? "onAllReady"
: "onShellReady";

return new Promise((resolve, reject) => {
let didError = false;

const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} />,
{
[callbackName]: () => {
const body = new PassThrough();

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(body, {
headers: responseHeaders,
status: didError ? 500 : responseStatusCode,
})
);

pipe(body);
},
onShellError: (err: unknown) => {
reject(err);
},
onError: (error: unknown) => {
didError = true;

responseHeaders.set("Content-Type", "text/html");
console.error(error);
},
}
);

return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders,
setTimeout(abort, ABORT_DELAY);
});
}
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"ics": "^2.40.0",
"imgproxy": "^1.0.0",
"inquirer": "^8.2.3",
"isbot": "^3.6.5",
"jsonschema": "^1.4.0",
"jszip": "^3.10.1",
"nodemailer": "^6.7.3",
Expand Down

0 comments on commit 7b1c10b

Please sign in to comment.