or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdclient-runtime.mddatabase.mde2e-testing.mdindex.mdrealtime.mdrouting.mdsynced-state.mdturnstile.mdvite-plugin.mdworker-runtime.md
tile.json

worker-runtime.mddocs/

Worker Runtime

The Worker Runtime provides the server-side execution environment for RedwoodSDK applications on Cloudflare Workers. It includes application definition, rendering, React Server Components support, and request context management.

Capabilities

Application Definition

Defines the main application with route handlers and middleware.

/**
 * Defines the main RedwoodSDK application
 * @param routes - Array of route definitions
 * @returns Application definition for Cloudflare Worker export
 */
function defineApp<T, Routes>(routes: Routes): AppDefinition<Routes, T>;

type AppDefinition<Routes, T> = {
  fetch(request: Request, env: any, ctx: ExecutionContext): Promise<Response>;
};

Usage Example:

// worker.tsx
import { defineApp, route, render } from 'rwsdk/worker';
import HomePage from './pages/HomePage';

function Document({ children }) {
  return (
    <html>
      <head>
        <title>My App</title>
      </head>
      <body>{children}</body>
    </html>
  );
}

export default defineApp([
  render(Document, [
    route('/', HomePage),
    route('/about', () => <h1>About Us</h1>),
  ]),
]);

Script Definition

Defines a worker script without routing for custom Worker implementations.

/**
 * Defines a worker script with custom fetch handler
 * @param fn - Custom fetch function
 * @returns Worker export
 */
function defineScript(
  fn: ({ env }: { env: any }) => Promise<unknown>
): () => Promise<unknown>;

Stream Rendering

Renders React elements to a ReadableStream for streaming SSR and RSC.

/**
 * Renders React elements to a streaming response
 * @param element - React element to render
 * @param options - Rendering options
 * @returns ReadableStream of rendered HTML/RSC payload
 */
function renderToStream(
  element: React.ReactElement,
  options?: RenderToStreamOptions
): Promise<ReadableStream>;

interface RenderToStreamOptions {
  /** Cloudflare environment bindings */
  env?: any;
  /** Request context */
  context?: any;
  /** Bundler map for module resolution */
  bundlerMap?: any;
}

Usage Example:

import { renderToStream } from 'rwsdk/worker';

async function handler(request: Request) {
  const stream = await renderToStream(<App />);
  return new Response(stream, {
    headers: { 'Content-Type': 'text/html' },
  });
}

String Rendering

Renders React elements to a complete HTML string for static or non-streaming SSR.

/**
 * Renders React elements to an HTML string
 * @param element - React element to render
 * @param options - Rendering options
 * @returns Complete HTML string
 */
function renderToString(
  element: React.ReactElement,
  options?: RenderToStringOptions
): Promise<string>;

interface RenderToStringOptions {
  /** Cloudflare environment bindings */
  env?: any;
  /** Request context */
  context?: any;
}

Request Context Access

Provides access to the current request information within server components and functions.

/**
 * Gets the current request information
 * @returns Current request info with params, context, env, and ctx
 */
function getRequestInfo<
  Params = unknown,
  AppContext = DefaultAppContext
>(): RequestInfo<Params, AppContext>;

/**
 * Global request info accessor (same as getRequestInfo)
 */
const requestInfo: typeof getRequestInfo;

interface RequestInfo<Params = unknown, AppContext = DefaultAppContext> {
  /** The incoming HTTP request */
  request: Request;
  /** Route parameters extracted from the URL */
  params: Params;
  /** Application context (can be customized per route) */
  context: AppContext;
  /** Cloudflare environment bindings (KV, DO, D1, etc.) */
  env: any;
  /** Execution context for waitUntil and passThroughOnException */
  ctx: ExecutionContext;
}

interface DefaultAppContext {
  [key: string]: any;
}

Usage Example:

import { getRequestInfo } from 'rwsdk/worker';

async function UserPage() {
  const { params, env } = getRequestInfo<{ id: string }>();

  const user = await env.DB.prepare(
    'SELECT * FROM users WHERE id = ?'
  ).bind(params.id).first();

  return <div>User: {user.name}</div>;
}

Request Context Utilities

Utilities for running code with specific request context or creating default request info.

/**
 * Runs a function with specific request context
 * @param nextRequestInfo - Request info to use
 * @param fn - Function to run with the context
 * @returns Result of the function
 */
function runWithRequestInfo<T>(
  nextRequestInfo: RequestInfo,
  fn: () => T
): T;

/**
 * Runs a function with partial request info overrides
 * @param overrides - Partial request info to override
 * @param fn - Function to run
 * @returns Result of the function
 */
function runWithRequestInfoOverrides<T>(
  overrides: PartialRequestInfo,
  fn: () => T
): T;

/**
 * Creates default request info with optional overrides
 * @param overrides - Partial overrides for default values
 * @returns Complete request info object
 */
function constructWithDefaultRequestInfo(
  overrides?: PartialRequestInfo
): RequestInfo;

type PartialRequestInfo<Params = unknown, AppContext = DefaultAppContext> = {
  request?: Request;
  params?: Params;
  context?: AppContext;
  env?: any;
  ctx?: ExecutionContext;
};

React Server Components Support

Functions for registering and handling React Server Components and server actions.

/**
 * Registers a server-side function for RSC
 * @param action - The server function
 * @param id - Unique module ID
 * @param name - Export name
 * @returns The registered function
 */
function registerServerReference(
  action: Function,
  id: string,
  name: string
): Function;

/**
 * Registers a client component reference
 * @param ssrModule - SSR module export
 * @param id - Module ID
 * @param exportName - Export name
 * @returns Client reference proxy
 */
function registerClientReference<Target>(
  ssrModule: Target,
  id: string,
  exportName: string
): any;

/**
 * Handles RSC server action requests
 * @param req - Incoming request
 * @returns Response with action result
 */
function rscActionHandler(req: Request): Promise<Response>;

Nonce Generation

Generates cryptographic nonces for Content Security Policy headers.

/**
 * Generates a cryptographic nonce for CSP
 * @returns Base64-encoded nonce string
 */
function generateNonce(): string;

Usage Example:

import { generateNonce } from 'rwsdk/worker';

function Document({ children }) {
  const nonce = generateNonce();

  return (
    <html>
      <head>
        <meta
          httpEquiv="Content-Security-Policy"
          content={`script-src 'nonce-${nonce}'`}
        />
      </head>
      <body>
        {children}
        <script nonce={nonce}>console.log('Safe script');</script>
      </body>
    </html>
  );
}

Error Handling

Class for HTTP error responses with status codes.

/**
 * Error response class for HTTP errors
 */
class ErrorResponse extends Error {
  constructor(code: number, message: string);
  code: number;
  message: string;
  name: string;
}

Usage Example:

import { ErrorResponse } from 'rwsdk/worker';

function requireAuth() {
  const user = getCurrentUser();
  if (!user) {
    throw new ErrorResponse(401, 'Unauthorized');
  }
}

Default Components

Pre-built Document components for common use cases.

/**
 * Default HTML document wrapper (minimal HTML5 structure)
 */
const DefaultDocument: React.ComponentType<DocumentProps>;

/**
 * Identity document that passes through children without wrapping
 */
const IdentityDocument: React.ComponentType<DocumentProps>;

/**
 * Default document for request info context
 */
const DefaultRequestInfoDocument: React.ComponentType<DocumentProps>;

Types

interface DocumentProps<T = any> {
  children: React.ReactNode;
  context?: T;
}