-
Notifications
You must be signed in to change notification settings - Fork 43
Cloudflare integration test #458
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 6 commits
8b249c0
2e54779
c8e9471
7826676
14dc600
c46fa38
4109d4f
4800755
9ca17e3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| .DS_Store | ||
| /node_modules/ | ||
|
|
||
| # React Router | ||
| /.react-router/ | ||
| /build/ | ||
|
|
||
| /worker-configuration.d.ts | ||
| /.wrangler |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| {"configPath":"../../build/server/wrangler.json","auxiliaryWorkers":[]} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| # React Router Cloudflare integration test | ||
|
|
||
| Useful to check if we run well on runtimes that don't support Node APIs such as `renderToPipeableStream`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { ApolloLink, HttpLink, InMemoryCache } from "@apollo/client/index.js"; | ||
| import { | ||
| createApolloLoaderHandler, | ||
| ApolloClient, | ||
| } from "@apollo/client-integration-react-router"; | ||
| import { IncrementalSchemaLink } from "@integration-test/shared/IncrementalSchemaLink"; | ||
| import { schema } from "@integration-test/shared/schema"; | ||
| import { delayLink } from "@integration-test/shared/delayLink"; | ||
| import { errorLink } from "@integration-test/shared/errorLink"; | ||
|
|
||
| const link = ApolloLink.from([ | ||
| delayLink, | ||
| errorLink, | ||
| typeof window === "undefined" | ||
| ? (new IncrementalSchemaLink({ schema }) as any as ApolloLink) | ||
| : new HttpLink({ uri: "/graphql" }), | ||
| ]); | ||
|
|
||
| export const makeClient = (request?: Request) => { | ||
| return new ApolloClient({ | ||
| cache: new InMemoryCache(), | ||
| link, | ||
| }); | ||
| }; | ||
| export const apolloLoader = createApolloLoaderHandler(makeClient); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { startTransition, StrictMode } from "react"; | ||
| import { hydrateRoot } from "react-dom/client"; | ||
| import { HydratedRouter } from "react-router/dom"; | ||
| import { makeClient } from "./apollo"; | ||
| import { ApolloProvider } from "@apollo/client/react/index.js"; | ||
|
|
||
| startTransition(() => { | ||
| const client = makeClient(); | ||
| hydrateRoot( | ||
| document, | ||
| <StrictMode> | ||
| <ApolloProvider client={client}> | ||
| <HydratedRouter /> | ||
| </ApolloProvider> | ||
| </StrictMode> | ||
| ); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import type { AppLoadContext, EntryContext } from "react-router"; | ||
| import { ServerRouter } from "react-router"; | ||
| import { isbot } from "isbot"; | ||
| import type { | ||
| RenderToPipeableStreamOptions, | ||
| RenderToReadableStreamOptions, | ||
| } from "react-dom/server"; | ||
| import { renderToReadableStream } from "react-dom/server"; | ||
| import { makeClient } from "./apollo"; | ||
| import { ApolloProvider } from "@apollo/client/react/index.js"; | ||
|
|
||
| export const streamTimeout = 5_000; | ||
| export type RenderOptions = { | ||
| [K in keyof RenderToReadableStreamOptions & | ||
| keyof RenderToPipeableStreamOptions]?: RenderToReadableStreamOptions[K]; | ||
| }; | ||
|
|
||
| export default async function handleRequest( | ||
| request: Request, | ||
| responseStatusCode: number, | ||
| responseHeaders: Headers, | ||
| routerContext: EntryContext, | ||
| loadContext: AppLoadContext, | ||
| // vercel-specific options, originating from `@vercel/react-router/entry.server.js` | ||
| options?: RenderOptions | ||
| ) { | ||
| let shellRendered = false; | ||
| const userAgent = request.headers.get("user-agent"); | ||
| const client = makeClient(request); | ||
|
|
||
| const abortController = new AbortController(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ported over the timeout logic from the other |
||
| setTimeout(() => { | ||
| abortController.abort(`Rendering exceed timeout of ${streamTimeout}ms`); | ||
| }, streamTimeout + 1000); | ||
|
|
||
| responseHeaders.set("Content-Type", "text/html"); | ||
|
|
||
| const stream = await renderToReadableStream( | ||
| <ApolloProvider client={client}> | ||
| <ServerRouter | ||
| context={routerContext} | ||
| url={request.url} | ||
| nonce={options?.nonce} | ||
| /> | ||
| </ApolloProvider>, | ||
| { | ||
| ...options, | ||
| signal: abortController.signal, | ||
| onError(error: unknown) { | ||
| responseStatusCode = 500; | ||
|
|
||
| if (shellRendered) { | ||
| console.error(error); | ||
| } | ||
| }, | ||
| } | ||
| ); | ||
| shellRendered = true; | ||
|
|
||
| // BUG: I tried to port this over /integration-test/react-router/app/entry.server.tsx | ||
| // But it breaks with a hydration error if I manually set shouldWaitForAllContent = true. | ||
| // Ensure requests from bots and SPA Mode renders wait for all content to load before responding | ||
| // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation | ||
| const shouldWaitForAllContent = (userAgent && isbot(userAgent)) || routerContext.isSpaMode; | ||
|
|
||
| if (shouldWaitForAllContent) { | ||
| await stream.allReady; | ||
| } | ||
|
|
||
| return new Response(stream, { | ||
| headers: responseHeaders, | ||
| status: responseStatusCode, | ||
| }) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { createRequestHandler } from "react-router"; | ||
|
|
||
| const requestHandler = createRequestHandler( | ||
| () => import("virtual:react-router/server-build"), | ||
| import.meta.env.MODE | ||
| ); | ||
|
|
||
| export default { | ||
| fetch(request, env, ctx) { | ||
| return requestHandler(request, { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Server entrypoint. |
||
| cloudflare: { env, ctx }, | ||
| }); | ||
| }, | ||
| } satisfies ExportedHandler<Env>; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import { | ||
| isRouteErrorResponse, | ||
| Links, | ||
| Meta, | ||
| Outlet, | ||
| Scripts, | ||
| ScrollRestoration, | ||
| } from "react-router"; | ||
|
|
||
| import type { Route } from "./+types/root"; | ||
| import { ApolloHydrationHelper } from "@apollo/client-integration-react-router"; | ||
|
|
||
| export function Layout({ children }: { children: React.ReactNode }) { | ||
| return ( | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charSet="utf-8" /> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1" /> | ||
| <Meta /> | ||
| <Links /> | ||
| </head> | ||
| <body> | ||
| <ApolloHydrationHelper>{children}</ApolloHydrationHelper> | ||
| <ScrollRestoration /> | ||
| <Scripts /> | ||
| </body> | ||
| </html> | ||
| ); | ||
| } | ||
|
|
||
| export default function App() { | ||
| return <Outlet />; | ||
| } | ||
|
|
||
| export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { | ||
| let message = "Oops!"; | ||
| let details = "An unexpected error occurred."; | ||
| let stack: string | undefined; | ||
|
|
||
| if (isRouteErrorResponse(error)) { | ||
| message = error.status === 404 ? "404" : "Error"; | ||
| details = | ||
| error.status === 404 | ||
| ? "The requested page could not be found." | ||
| : error.statusText || details; | ||
| } else if (import.meta.env.DEV && error && error instanceof Error) { | ||
| details = error.message; | ||
| stack = error.stack; | ||
| } | ||
|
|
||
| return ( | ||
| <main className="pt-16 p-4 container mx-auto"> | ||
| <h1>{message}</h1> | ||
| <p>{details}</p> | ||
| {stack && ( | ||
| <pre className="w-full p-4 overflow-x-auto"> | ||
| <code>{stack}</code> | ||
| </pre> | ||
| )} | ||
| </main> | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { flatRoutes } from "@react-router/fs-routes"; | ||
|
|
||
| export default flatRoutes(); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import { useLoaderData } from "react-router"; | ||
| import type { Route } from "./+types/_index"; | ||
| import { | ||
| useApolloClient, | ||
| useQueryRefHandlers, | ||
| useReadQuery, | ||
| } from "@apollo/client/react/index.js"; | ||
| import { apolloLoader } from "~/apollo"; | ||
| import { DEFERRED_QUERY } from "@integration-test/shared/queries"; | ||
| import { useTransition } from "react"; | ||
|
|
||
| export const loader = apolloLoader<Route.LoaderArgs>()(({ preloadQuery }) => { | ||
| const queryRef = preloadQuery(DEFERRED_QUERY, { | ||
| variables: { delayDeferred: 1000 }, | ||
| }); | ||
| return { | ||
| queryRef, | ||
| }; | ||
| }); | ||
|
|
||
| export default function Home() { | ||
| const { queryRef } = useLoaderData<typeof loader>(); | ||
|
|
||
| const { refetch } = useQueryRefHandlers(queryRef); | ||
| const [refetching, startTransition] = useTransition(); | ||
| const { data } = useReadQuery(queryRef); | ||
| const client = useApolloClient(); | ||
|
|
||
| return ( | ||
| <> | ||
| <ul> | ||
| {data.products.map(({ id, title, rating }) => ( | ||
| <li key={id}> | ||
| {title} | ||
| <br /> | ||
| Rating:{" "} | ||
| <div style={{ display: "inline-block", verticalAlign: "text-top" }}> | ||
| {rating?.value || ""} | ||
| <br /> | ||
| {rating ? `Queried in ${rating.env} environment` : "loading..."} | ||
| </div> | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| <p>Queried in {data.env} environment</p> | ||
| <button | ||
| disabled={refetching} | ||
| onClick={() => { | ||
| client.cache.batch({ | ||
| update(cache) { | ||
| for (const product of data.products) { | ||
| cache.modify({ | ||
| id: cache.identify(product), | ||
| fields: { | ||
| rating: () => null, | ||
| }, | ||
| }); | ||
| } | ||
| }, | ||
| }); | ||
| startTransition(() => { | ||
| refetch(); | ||
| }); | ||
| }} | ||
| > | ||
| {refetching ? "refetching..." : "refetch"} | ||
| </button> | ||
| </> | ||
| ); | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.