Example 1
Example 1
import { ReactRouterPlugin } from '@setu-ts/react-router-plugin'; import { CAPABILITIES, ISsrService } from '@setu-ts/common'; const app = createApplication(); app.register(ReactRouterPlugin({ serverBuildPath: './build/server/index.js', assetsDir: './build/client/assets', })); await app.start({ port: 3000 });
Implements ISsrService.
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
Pure function that assembles an RR request handler from a pre-loaded build
and the createRequestHandler factory.
Validates that an injected loadRequestHandler resolved to a usable
SsrRuntime, and narrows it.
Bridges a kernel IRequestContext into a web Request, invokes the RR
handler, and maps the resulting web Response back onto ctx.response.
Returns the context key for a name, creating it on first use.
Builds the per-request context factory from React Router's
RouterContextProvider class.
Creates a handler that ATTEMPTS to serve a file from a directory, resolving
the request path relative to createPublicFileHandler.options.assetsDir.
The plugin passes the CLIENT-BUILD ROOT here (the parent of the assets dir,
where Vite copies public/) — probing the assets subdir itself missed every
public file.
Creates a static-asset RouteHandler that serves files from a directory
using the injected IFileSystem.
Default implementation of loadRequestHandler.
Creates the ReactRouterPlugin.
Opaque marker returned by IResponse terminal methods and
expected back from route handlers. It exists purely so the type system can
verify a handler produced a response; only the kernel creates values of
this type.
-
__handlerResult: true
Brand preventing accidental structural matches.
Runtime-agnostic file system operations. Absent on runtimes without file system access (edge platforms).
-
mkdir(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Creates a directory.
-
readFile(path: string): Promise<Uint8Array>
Reads a file.
-
readStream(): Promise<ReadableStream<Uint8Array>>path: string,options?: { readonly start?: number; readonly end?: number; }
Reads a file as a stream, optionally with byte range.
-
readdir(path: string): Promise<readonly string[]>
Lists directory entries.
-
realPath(path: string): Promise<string>
Resolves a path to its canonical absolute form, following symlinks.
-
rm(): Promise<void>path: string,options?: { readonly recursive?: boolean; }
Removes a file or directory.
-
stat(path: string): Promise<StatResult>
Returns file metadata.
-
writeFile(): Promise<void>path: string,data: Uint8Array
Writes a file, creating it if absent.
Per-request context passed to middleware and route handlers. Each request gets a fresh context; request-scoped data lives here, never in globals.
-
id: string
Unique request ID (generated or propagated by middleware).
-
params: Readonly<Record<string, string>>
Path parameters extracted by the router (e.g.
:id). -
query: Readonly<Record<string, string>>
Query string parameters.
-
raw: Request
The undisturbed web-standard
Request, preserved for WebSocket upgrade and gRPC dispatch after the middleware pipeline. -
request: IRequest
The incoming request.
-
response: IResponse
The response builder.
-
services: IServiceRegistry
Service resolution (application-scoped plus request-scoped services).
-
signal: AbortSignal
An abort signal that fires when the underlying HTTP connection is severed (client disconnect, timeout). Populated by the kernel's request-context factory from the native
Request.signal; falls back to a non-aborting sentinel so handlers always have a live signal to listen on. -
startTime: number
High-resolution timestamp captured when the context was created.
-
state: Map<string, unknown>
Request-scoped state for passing data between middleware and handlers.
Service contract for server-side rendering (SSR).
-
render(ctx: IRequestContext): Promise<HandlerResult>
Renders an SSR document for the given request context.
Options for the React Router plugin.
-
assetUrlPrefix: string
URL prefix for the static-asset route. Default
/assets/. -
assetsDir: string
Filesystem root of the built client bundle. Omit to disable static-asset serving (no asset route registered).
-
basename: string
Mount prefix for the SSR catch-all route. Default
/. MUST match the app'sreact-router.config.tsbasenamefor flat/nested routes to resolve. -
loadRequestHandler: () => Promise<SsrRuntime>serverBuildPath: string,mode: string
Injectable seam for lazy loading the RR runtime. When omitted, the default performs
await import(serverBuildPath)+await import('npm:react-router@8'). -
mode: "production" | "development"
Mode passed to
createRequestHandler(build, mode). -
populateLoadContext: PopulateLoadContext
Adds application values to the per-request React Router context, on top of the
servicesContextanduserContextkeys the plugin always sets. -
publicFiles: boolean
Also serves files from the client-build ROOT — where Vite copies
public/(robots.txt,favicon.ico, …) — in addition toReactRouterPluginOptions.assetUrlPrefix, withCache-Control: public, max-age=0, must-revalidate: root files are not content-hashed, so they must be revalidated rather than cached immutably. A request matching neither the root nor the prefix still falls through to the SSR catch-all. -
serverBuildPath: string
Path to the React Router Vite server build (default export =
ServerBuild).
A React Router context key, used by identity as the argument to
RouterLoadContext.get / RouterLoadContext.set.
-
defaultValue: T
Value returned by
get()when the key has not been set.
The per-request context object React Router passes to loaders, actions, and
middleware as context.
-
get<T>(key: RouterContextKey<T>): T
Reads a key, falling back to the key's
defaultValue. -
set<T>(): voidkey: RouterContextKey<T>,value: T
Writes a key, overwriting any previous value.
Everything the plugin needs from a loaded React Router module: the request
handler, plus a factory for the RouterContextProvider that handler will
accept.
-
createLoadContext: () => RouterLoadContext
Constructs a fresh, empty per-request context provider.
-
handler: SsrRequestHandler
The callable returned by
createRequestHandler(build, mode).
Hook for adding application values to the per-request React Router context.
A route handler: receives the request context and returns a response via the context's response builder.
React Router request handler — the callable returned by
createRequestHandler(build, mode).
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
Key holding the kernel IServiceRegistry for the current request.
Key holding the authenticated principal, or null on an anonymous request.
Usage
import * as React_Router_v7_plugin___embeds_React_Router_framework_mode_as_a_first_party_plugin_so_a_Setu_TS_application_can_serve_a_React_frontend_with_SSR_and_file_based_routing__ from "react-router-plugin/src/index.ts";