Skip to content

Commit

Permalink
chore: add entry.server.tsx to functions template
Browse files Browse the repository at this point in the history
  • Loading branch information
pieh committed Mar 29, 2024
1 parent 65f7e25 commit 51efb7a
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions remix.init/functions/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { PassThrough } from "node:stream";

import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";

const ABORT_DELAY = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
const bot = isbot(request.headers.get("user-agent"));
return new Promise((resolve, reject) => {
let shellRendered = false;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onShellReady() {
if (!bot) {
shellRendered = true;
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
pipe(body);
}
},
onShellError(error: unknown) {
reject(error);
},
onAllReady() {
// Avoid a bug where responses aren't flushed if there's an outstanding timer.
clearTimeout(timer);
if (bot) {
shellRendered = true;
responseHeaders.set("Content-Type", "text/html");
resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);
pipe(body);
}
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);

const timer = setTimeout(() => {
abort();
}, ABORT_DELAY);
});
}

0 comments on commit 51efb7a

Please sign in to comment.