TanStack React Start Server and Router Setup Architecture in OpenSEO
OpenSEO builds its web application on TanStack React Start, combining server-side rendering (SSR), type-safe routing via TanStack Router, and server-only functions within a single Cloudflare Worker runtime.
The OpenSEO repository implements a three-layer architecture that separates concerns between the Start instance configuration, the server handler entry point, and the client-side router. This setup enables full-stack type safety, streaming server rendering, and seamless server function calls from the client.
The Three-Layer Architecture
OpenSEO organizes its TanStack React Start implementation into distinct layers:
- Start Instance (
src/start.ts): Boots the runtime, registers global middleware including CSRF protection, and exposes the configuration used across the application. - Server Handler (
src/server.ts): Provides the Cloudflare Worker entry point, wrapping the Start instance in a streaming handler while managing OAuth, agency routing, and database connections. - Router (
src/router.tsx): Generates a type-safe route tree from file-based routes and creates the TanStack Router that hydrates on the client.
The Start Instance Layer
The foundation of the architecture lives in src/start.ts, where OpenSEO creates the Start instance using createStart from @tanstack/react-start.
import { createCsrfMiddleware, createStart } from "@tanstack/react-start";
const csrfMiddleware = createCsrfMiddleware({
filter: (ctx) => ctx.handlerType === "serverFn",
});
export const startInstance = createStart(() => ({
requestMiddleware: [csrfMiddleware],
functionMiddleware: globalServerFunctionMiddleware,
}));
This configuration applies CSRF protection to all server functions through createCsrfMiddleware, filtering specifically for serverFn handler types. The globalServerFunctionMiddleware injects shared context such as database connections and authentication state into every server function invocation.
The exported startInstance object serves as the central configuration hub that both the server handler and server functions reference throughout the application lifecycle.
The Server Handler Layer
The Cloudflare Worker entry point resides in src/server.ts, where OpenSEO constructs the streaming SSR handler and routes incoming requests.
import {
createStartHandler,
defaultStreamHandler,
} from "@tanstack/react-start/server";
const appFetch = createStartHandler(defaultStreamHandler);
const openSeoOAuthProvider = createOpenSeoOAuthProvider(appFetch);
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
// … auth-mode detection, self-host routing, GDPR, etc.
return handleFetch(request, env, ctx);
},
};
The implementation follows a specific sequence:
createStartHandlerbuilds theappFetchstreaming handler usingdefaultStreamHandlerfor SSR.- OAuth provider initialization attaches authentication capabilities for hosted mode deployments.
handleFetchinspects URLs and dispatches to specialized routes including GDPR erasure endpoints (/gdpr-storage-erasure), Agent Durable Objects (/agents/*), and self-host MCP routes before falling back to the SSR handler.
This layer handles the runtime boundary between Cloudflare's Worker environment and the React application, managing execution context, environment variables, and request routing logic.
The Router Layer
Client-side navigation relies on src/router.tsx, which instantiates TanStack Router using the generated route tree.
import { createRouter as createTanStackRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
export function getRouter() {
const router = createTanStackRouter({
routeTree,
defaultPreload: "intent",
defaultErrorComponent: DefaultCatchBoundary,
defaultNotFoundComponent: () => <NotFound />,
scrollRestoration: true,
});
return router;
}
The router configuration enables intent-based preloading, where data fetches trigger only when the user shows clear navigation intent. It also provides default error boundaries through DefaultCatchBoundary and 404 handling via the NotFound component, while preserving scroll position across navigations for native-like behavior.
The routeTree import comes from src/routeTree.gen.ts, an auto-generated file that TanStack Router updates whenever files in src/routes/ change, ensuring type safety across the entire route hierarchy.
Server Functions Architecture
OpenSEO implements server-only logic through createServerFn from @tanstack/react-start, housed in src/serverFunctions/*.ts files.
// src/serverFunctions/keywords.ts
import { createServerFn } from "@tanstack/react-start";
export const fetchKeywords = createServerFn(async (projectId: string) => {
// ... DB queries, external API calls, etc.
});
These functions execute exclusively on the server within the same Cloudflare Worker context that handles SSR. The Start instance's middleware pipeline—including CSRF protection and database context—injects automatically into each function call. Client components consume these functions via useServerFn hooks, maintaining type safety across the network boundary.
How the Pieces Fit Together
The architecture flows through a specific request lifecycle:
- Cloudflare Worker receives an HTTP request at
src/server.ts. handleFetchdetermines the appropriate sub-handler (OAuth, agents, or SSR).- For page requests,
appFetchprocesses the request using the Start instance configuration fromsrc/start.ts. - The Start instance renders the React tree on the server, embedding the client router configuration.
- The browser receives HTML containing the hydrated TanStack Router (
src/router.tsx), which uses the samerouteTreefor seamless client-side navigation. - Subsequent server function calls route through the Start instance's middleware stack and execute within the Worker context.
Practical Implementation Examples
Defining a New Server Function
Create type-safe server logic that automatically receives request context:
// src/serverFunctions/example.ts
import { createServerFn } from "@tanstack/react-start";
export const helloWorld = createServerFn(async (name: string) => {
return { message: `Hello, ${name}!` };
});
Consuming Server Functions in Components
Access server data with automatic loading and error states:
import { useServerFn } from "@tanstack/react-start";
import { helloWorld } from "@/serverFunctions/example";
export function Greeting() {
const { data, error, isLoading } = useServerFn(helloWorld, "Alice");
if (isLoading) return <div>Loading…</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{data?.message}</div>;
}
Adding File-Based Routes
Create new routes through filesystem placement:
- Create
src/routes/_app/example.tsx:
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/example")({
component: () => <h1>OpenSEO Example Page</h1>,
});
- TanStack Router auto-generates the type definitions in
src/routeTree.gen.ts, making the route immediately available without manual router configuration.
Implementing Custom Middleware
Extend the Start instance with request logging or auditing:
// src/start.ts
import { createStart } from "@tanstack/react-start";
export const startInstance = createStart(() => ({
requestMiddleware: [
(ctx, next) => {
console.log("Incoming request:", ctx.request.method, ctx.request.url);
return next();
},
],
}));
This middleware executes for every request including server functions, enabling cross-cutting concerns like logging, metrics, or authentication verification.
Summary
- Start Instance (
src/start.ts): Configures the TanStack React Start runtime with CSRF middleware and global server function context. - Server Handler (
src/server.ts): Cloudflare Worker entry point managing streaming SSR, OAuth routing, and request dispatching. - Router (
src/router.tsx): Hydrates the TanStack Router with auto-generated type-safe routes and intent-based preloading. - Server Functions: Execute within the Worker environment via
createServerFn, callable from client components throughuseServerFn. - File-Based Routing: Routes defined in
src/routes/automatically generate TypeScript definitions insrc/routeTree.gen.ts.
Frequently Asked Questions
How does OpenSEO handle CSRF protection in TanStack React Start?
OpenSEO implements CSRF protection through the createCsrfMiddleware function in src/start.ts, filtering specifically for serverFn handler types. This middleware automatically validates cross-site request forgery tokens on all server function invocations while allowing regular page requests to pass through unimpeded.
What is the difference between createStartHandler and createStart in the OpenSEO architecture?
createStart (used in src/start.ts) boots the TanStack React Start runtime and configures middleware pipelines, while createStartHandler (used in src/server.ts) builds the actual HTTP request handler that Cloudflare Workers invoke. The Start instance provides configuration; the Start handler processes incoming requests using that configuration.
How does file-based routing work with TypeScript type safety?
TanStack Router scans the src/routes/ directory and auto-generates src/routeTree.gen.ts, which contains TypeScript definitions for every route, its parameters, and hierarchical relationships. When developers import routeTree into src/router.tsx, the createTanStackRouter function uses these definitions to enforce type safety on route navigation, parameters, and search queries.
Can server functions access the database and authentication context?
Yes. Server functions defined with createServerFn execute within the same Cloudflare Worker context as the SSR handler. The globalServerFunctionMiddleware registered in src/start.ts automatically injects database connections, authentication state, and other context into every server function invocation, making these resources available without manual passing.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →