Skip to content
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

feat: add support for React Router #33

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ node_modules
.wrangler
.mf
*.tgz
dist
dist
.react-router
10 changes: 10 additions & 0 deletions examples/react-router/cloudflare-pages/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
node_modules

test-results

/.cache
/build
.env
.dev.vars

.wrangler
18 changes: 18 additions & 0 deletions examples/react-router/cloudflare-pages/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.client
*/

import { startTransition, StrictMode } from 'react'
import { hydrateRoot } from 'react-dom/client'
import { HydratedRouter } from 'react-router/dom'

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter />
</StrictMode>
)
})
44 changes: 44 additions & 0 deletions examples/react-router/cloudflare-pages/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* By default, Remix will handle generating the HTTP Response for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.server
*/

import { isbot } from 'isbot'
// @ts-expect-error `react-dom/server.browser` is not typed
import { renderToReadableStream } from 'react-dom/server.browser'
import type { AppLoadContext, EntryContext } from 'react-router'
import { ServerRouter } from 'react-router'

export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
const body = await renderToReadableStream(
<ServerRouter context={remixContext} url={request.url} />,
{
signal: request.signal,
onError(error: unknown) {
// Log streaming rendering errors from inside the shell
console.error(error)
responseStatusCode = 500
},
}
)

if (isbot(request.headers.get('user-agent') || '')) {
await body.allReady
}

responseHeaders.set('Content-Type', 'text/html')
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
})
}
20 changes: 20 additions & 0 deletions examples/react-router/cloudflare-pages/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Outlet, Scripts } from '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' />
</head>
<body>
{children}
<Scripts />
</body>
</html>
)
}

export default function App() {
return <Outlet />
}
7 changes: 7 additions & 0 deletions examples/react-router/cloudflare-pages/app/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { index } from '@react-router/dev/routes'
import type {RouteConfig} from '@react-router/dev/routes'

export default [
index('routes/_index.tsx'),

] satisfies RouteConfig
26 changes: 26 additions & 0 deletions examples/react-router/cloudflare-pages/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useLoaderData } from 'react-router'
import type { Route } from './+types/_index'

export const loader = (args: Route.LoaderArgs) => {
const extra = args.context.extra
const cloudflare = args.context.cloudflare
const myVarInVariables = args.context.hono.context.get('MY_VAR_IN_VARIABLES')
return { cloudflare, extra, myVarInVariables }
}

export default function Index() {
const { cloudflare, extra, myVarInVariables } = useLoaderData<typeof loader>()
return (
<div>
<h1>Remix and Hono</h1>
<h2>Var is {cloudflare.env.MY_VAR}</h2>
<h3>
{cloudflare.cf ? 'cf,' : ''}
{cloudflare.ctx ? 'ctx,' : ''}
{cloudflare.caches ? 'caches are available' : ''}
</h3>
<h4>Extra is {extra}</h4>
<h5>Var in Variables is {myVarInVariables}</h5>
</div>
)
}
30 changes: 30 additions & 0 deletions examples/react-router/cloudflare-pages/e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { expect, test } from '@playwright/test'

test('Should return 200 response - /', async ({ page }) => {
const response = await page.goto('/')
expect(response?.status()).toBe(200)

const headers = response?.headers() ?? {}
expect(headers['x-powered-by']).toBe('Remix and Hono')

const contentH1 = await page.textContent('h1')
expect(contentH1).toBe('Remix and Hono')

const contentH2 = await page.textContent('h2')
expect(contentH2).toBe('Var is My Value')

const contentH3 = await page.textContent('h3')
expect(contentH3).toBe('cf,ctx,caches are available')

const contentH4 = await page.textContent('h4')
expect(contentH4).toBe('Extra is stuff')

const contentH5 = await page.textContent('h5')
expect(contentH5).toBe('Var in Variables is My variable set in c.set')
})

test('Should return 200 response - /api', async ({ page }) => {
const response = await page.goto('/api')
expect(response?.status()).toBe(200)
expect(await response?.json()).toEqual({ message: 'Hello', var: 'My Value' })
})
7 changes: 7 additions & 0 deletions examples/react-router/cloudflare-pages/functions/[[path]].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// functions/[[path]].ts
import handle from 'hono-remix-adapter/cloudflare-pages'
import { getLoadContext } from 'load-context'
import * as build from '../build/server'
import server from '../server'

export const onRequest = handle(build, server, { getLoadContext })
40 changes: 40 additions & 0 deletions examples/react-router/cloudflare-pages/load-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Context } from 'hono'
import type { AppLoadContext } from 'react-router'
import type { PlatformProxy } from 'wrangler'

type Env = {
Bindings: {
MY_VAR: string
}
Variables: {
MY_VAR_IN_VARIABLES: string
}
}

type Cloudflare = Omit<PlatformProxy<Env['Bindings']>, 'dispose'>

declare module 'react-router' {
interface AppLoadContext {
cloudflare: Cloudflare
extra: string
hono: {
context: Context<Env>
}
}
}

type GetLoadContext = (args: {
request: Request
context: {
cloudflare: Cloudflare
hono: { context: Context<Env> }
}
}) => AppLoadContext

// Shared implementation compatible with Vite, Wrangler, and Cloudflare Pages
export const getLoadContext: GetLoadContext = ({ context }) => {
return {
...context,
extra: 'stuff',
}
}
40 changes: 40 additions & 0 deletions examples/react-router/cloudflare-pages/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "example-cloudflare-pages-react-router",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"build": "react-router build",
"deploy": "npm run build && wrangler pages deploy",
"dev": "react-router dev",
"start": "wrangler pages dev ./build/client",
"typecheck": "tsc",
"preview": "npm run build && wrangler pages dev",
"test:e2e:vite": "playwright test -c playwright-vite.config.ts e2e.test.ts",
"test:e2e:pages": "npm run build && playwright test -c playwright-pages.config.ts e2e.test.ts"
},
"dependencies": {
"@react-router/cloudflare": "^7.0.1",
"hono": "^4.5.11",
"isbot": "^4.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"remix-hono": "^0.0.16",
"react-router": "^7.0.1"
},
"devDependencies": {
"@hono/vite-dev-server": "^0.16.0",
"@playwright/test": "^1.48.2",
"@react-router/dev": "^7.0.1",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"playwright": "^1.47.0",
"typescript": "^5.1.6",
"vite": "^5.1.0",
"vite-tsconfig-paths": "^4.2.1",
"wrangler": "3.57.1"
},
"engines": {
"node": ">=20.0.0"
}
}
26 changes: 26 additions & 0 deletions examples/react-router/cloudflare-pages/playwright-pages.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { defineConfig, devices } from '@playwright/test'

const port = 8798

export default defineConfig({
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
use: {
baseURL: `http://localhost:${port.toString()}`,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
timeout: 5000,
retries: 2,
},
],
webServer: {
command: `npm exec wrangler pages dev -- --port ${port.toString()}`,
port,
reuseExistingServer: !process.env.CI,
},
})
26 changes: 26 additions & 0 deletions examples/react-router/cloudflare-pages/playwright-vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { defineConfig, devices } from '@playwright/test'

const port = 6173

export default defineConfig({
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
use: {
baseURL: `http://localhost:${port.toString()}`,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
timeout: 5000,
retries: 2,
},
],
webServer: {
command: `npm exec vite -- --port ${port.toString()} -c ./vite.config.ts`,
port,
reuseExistingServer: !process.env.CI,
},
})
26 changes: 26 additions & 0 deletions examples/react-router/cloudflare-pages/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// server/index.ts
import { Hono } from 'hono'

const app = new Hono<{
Bindings: {
MY_VAR: string
}
Variables: {
MY_VAR_IN_VARIABLES: string
}
}>()

app.use(async (c, next) => {
c.set('MY_VAR_IN_VARIABLES', 'My variable set in c.set')
await next()
c.header('X-Powered-By', 'Remix and Hono')
})

app.get('/api', (c) => {
return c.json({
message: 'Hello',
var: c.env.MY_VAR,
})
})

export default app
45 changes: 45 additions & 0 deletions examples/react-router/cloudflare-pages/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"include": [
"**/*.ts",
"**/*.tsx",
"**/.server/**/*.ts",
"**/.server/**/*.tsx",
"**/.client/**/*.ts",
"**/.client/**/*.tsx"
],
"compilerOptions": {
"lib": [
"DOM",
"DOM.Iterable",
"ES2022"
],
"types": [
"@react-router/cloudflare",
"vite/client",
"@cloudflare/workers-types/2023-07-01"
],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"target": "ES2022",
"strict": true,
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"rootDirs": [
".",
"./.react-router/types"
],
"baseUrl": ".",
"paths": {
"~/*": [
"./app/*"
]
},
// Vite takes care of building everything, not tsc.
"noEmit": true
}
}
Loading