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(remix): Add Worker Runtime support to Remix SDK. #9225

Closed
wants to merge 13 commits into from
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: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,9 @@ jobs:
'sveltekit',
'generic-ts3.8',
'node-experimental-fastify-app',
'remix-cloudflare-workers',
'remix-cloudflare-pages',
'remix-hydrogen',
]
build-command:
- false
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('eslint').Linter.Config} */
module.exports = {
extends: ['@remix-run/eslint-config', '@remix-run/eslint-config/node'],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
node_modules

/.cache
/functions/\[\[path\]\].js
/functions/\[\[path\]\].js.map
/functions/metafile.*
/functions/version.txt
/public/build
.dev.vars
env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@sentry:registry=http://localhost:4873
@sentry-internal:registry=http://localhost:4873
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* 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 { RemixBrowser, useLocation, useMatches } from '@remix-run/react';
import { startTransition, StrictMode, useEffect } from 'react';
import { hydrateRoot } from 'react-dom/client';
import * as Sentry from '@sentry/remix';
import { env } from '../env';

Sentry.init({
dsn: env.SENTRY_DSN,
integrations: [
new Sentry.BrowserTracing({
routingInstrumentation: Sentry.remixRouterInstrumentation(useEffect, useLocation, useMatches),
}),
new Sentry.Replay(),
],
// Performance Monitoring
tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!
// Session Replay
replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
});

Sentry.addGlobalEventProcessor(event => {
if (
event.type === 'transaction' &&
(event.contexts?.trace?.op === 'pageload' || event.contexts?.trace?.op === 'navigation')
) {
const eventId = event.event_id;
if (eventId) {
window.recordedTransactions = window.recordedTransactions || [];
window.recordedTransactions.push(eventId);
}
}

return event;
});

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>,
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* 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 type { AppLoadContext, EntryContext, DataFunctionArgs } from '@remix-run/cloudflare';
import { RemixServer } from '@remix-run/react';
import isbot from 'isbot';
import { renderToReadableStream } from 'react-dom/server';
import * as Sentry from '@sentry/remix';
import { env } from '../env';

Sentry.workerInit({
dsn: env.SENTRY_DSN,
// Performance Monitoring
tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!
debug: true,
});

export function handleError(error: unknown, { request }: DataFunctionArgs): void {
Sentry.captureRemixServerException(error, 'remix.server', request);
}

export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
loadContext: AppLoadContext,
) {
const body = await renderToReadableStream(<RemixServer 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,
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { LinksFunction } from '@remix-run/cloudflare';
import { cssBundleHref } from '@remix-run/css-bundle';
import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData } from '@remix-run/react';
import { withSentry } from '@sentry/remix';

export const links: LinksFunction = () => [...(cssBundleHref ? [{ rel: 'stylesheet', href: cssBundleHref }] : [])];

function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}

export default withSentry(App);
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as Sentry from '@sentry/remix';
import { Link, useRouteError } from '@remix-run/react';

export default function Index() {
return (
<div>
<input
type="button"
value="Capture Exception"
id="exception-button"
onClick={() => {
const eventId = Sentry.captureException(new Error('I am an error!'));
window.capturedExceptionId = eventId;
}}
/>
<Link to="/user/5" id="navigation">
navigate
</Link>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useRouteError } from '@remix-run/react';
import { captureRemixErrorBoundaryError } from '@sentry/remix';
import { useState } from 'react';

export function ErrorBoundary() {
const error = useRouteError();
const eventId = captureRemixErrorBoundaryError(error);

return (
<div>
<span>ErrorBoundary Error</span>
<span id="event-id">{eventId}</span>
</div>
);
}

export default function ErrorBoundaryCapture() {
const [count, setCount] = useState(0);

if (count > 0) {
throw new Error('Sentry React Component Error');
} else {
setTimeout(() => setCount(count + 1), 0);
}

return <div>{count}</div>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { LoaderFunction } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';

export const loader: LoaderFunction = async ({ params: { id } }) => {
if (id === '-1') {
throw new Error('Unexpected Server Error');
}

return null;
};

export default function LoaderError() {
const data = useLoaderData();

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { json } from '@remix-run/cloudflare';
import { useLoaderData } from '@remix-run/react';
import * as Sentry from '@sentry/remix';

export function loader() {
const id = Sentry.captureException(new Error('Sentry Server Error'));

return json({ id });
}

export default function ServerError() {
const { id } = useLoaderData();

return (
<div>
<pre id="event-id">{id}</pre>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function User() {
return <div>I am a blank page</div>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# export environment variables from .env file

# exit if any command fails
set -e

# create environment variables file
cat >./env.ts <<EOF
export const env = {
SENTRY_DSN: '${E2E_TEST_DSN}',
};
EOF
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
interface Window {
recordedTransactions?: string[];
capturedExceptionId?: string;
ENV: {
SENTRY_DSN: string;
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "remix-cloudflare",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"build": "remix build",
"dev": "remix dev --manual -c \"npm run start\"",
"start": "wrangler pages dev ./public --compatibility-date=2023-06-21",
"typecheck": "tsc",
"pages:deploy": "npm run build && wrangler pages deploy ./public",
"test:prepare": "./createEnvFile.sh",
"test:build": "pnpm install && npx playwright install && pnpm test:prepare && pnpm build",
"test:assert": "pnpm playwright test"
},
"dependencies": {
"@sentry/remix": "latest || *",
"@remix-run/cloudflare": "2.0.0",
"@remix-run/cloudflare-pages": "2.0.0",
"@remix-run/css-bundle": "2.0.0",
"@remix-run/react": "2.0.0",
"isbot": "^3.6.8",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20230518.0",
"@playwright/test": "^1.36.2",
"@remix-run/dev": "2.0.0",
"@remix-run/eslint-config": "^2.0.1",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"eslint": "^8.38.0",
"esm-loader-typescript": "1.0.5",
"typescript": "^5.1.0",
"wrangler": "^3.12.0"
},
"engines": {
"node": ">=18.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';

const port = 3030;

/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 150_000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: 0,
/* Opt out of parallel tests on CI. */
workers: 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'list',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},

/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
// For now we only test Chrome!
],

/* Run your local dev server before starting the tests */
webServer: {
command: `pnpm start --port=${port}`,
port,
},
};

export default config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/favicon.ico
Cache-Control: public, max-age=3600, s-maxage=3600
/build/*
Cache-Control: public, max-age=31536000, immutable
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"version": 1,
"include": ["/*"],
"exclude": ["/favicon.ico", "/build/*"]
}
Binary file not shown.
Loading
Loading