-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add entry.server.tsx to functions template
- Loading branch information
Showing
1 changed file
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
} |