- Spec files
npm-tanstack--react-start
Describes: pkg:npm/@tanstack/react-start@1.132.x
- Description
- Modern full-stack React framework with SSR, streaming, server functions, and API routes powered by TanStack Router and Vite.
- Author
- tessl
- Last updated
How to use
npx @tessl/cli registry install tessl/npm-tanstack--react-start@1.132.0
ssr-components.md docs/
1# SSR Components23SSR (Server-Side Rendering) components provide the foundation for rendering React applications on both server and client sides. These components handle hydration, streaming, and the coordination between server and client rendering processes.45## Capabilities67### StartClient Component89The main client-side React component that handles hydration and router initialization for client-side rendering.1011```typescript { .api }12/**13* Client-side root component for hydrating the application14* Automatically handles router hydration and initial render15* @returns JSX.Element - The hydrated client application16*/17function StartClient(): JSX.Element;18```1920**Usage Examples:**2122```typescript23import { StrictMode, startTransition } from "react";24import { hydrateRoot } from "react-dom/client";25import { StartClient } from "@tanstack/react-start/client";2627// Basic client hydration28startTransition(() => {29hydrateRoot(30document,31<StrictMode>32<StartClient />33</StrictMode>34);35});3637// Custom root element hydration38const rootElement = document.getElementById("app");39if (rootElement) {40hydrateRoot(rootElement, <StartClient />);41}42```4344### StartServer Component4546The main server-side React component that provides the router for server-side rendering.4748```typescript { .api }49/**50* Server-side root component for SSR51* @param props - Configuration object with router instance52* @returns JSX.Element - The server-rendered application53*/54function StartServer<TRouter extends AnyRouter>(props: {55router: TRouter;56}): JSX.Element;5758interface AnyRouter {59// Router instance from TanStack Router60state: RouterState;61options: RouterOptions;62history: RouterHistory;63}64```6566**Usage Examples:**6768```typescript69import { StartServer } from "@tanstack/react-start/server";70import { createRouter } from "@tanstack/react-router";7172// Create router instance73const router = createRouter({74routeTree: rootRoute,75context: {76// Server context77}78});7980// Server-side rendering81function renderApp() {82return <StartServer router={router} />;83}8485// In server handler86export default {87fetch: async (request) => {88const html = ReactDOMServer.renderToString(<StartServer router={router} />);89return new Response(html, {90headers: { "content-type": "text/html" }91});92}93};94```9596### Create Start Handler9798Creates a request handler for the server that processes incoming requests and renders the application.99100```typescript { .api }101/**102* Creates the main request handler for server-side processing103* @param streamHandler - Optional custom streaming handler104* @returns RequestHandler for processing HTTP requests105*/106function createStartHandler(107streamHandler?: StreamHandler108): RequestHandler<Register>;109110interface RequestHandler<TRegister> {111(request: Request): Promise<Response>;112router?: AnyRouter;113}114115interface StreamHandler {116(renderOptions: RenderOptions): ReadableStream | Promise<ReadableStream>;117}118119interface RenderOptions {120router: AnyRouter;121request: Request;122responseHeaders: Headers;123}124```125126**Usage Examples:**127128```typescript129import {130createStartHandler,131defaultStreamHandler132} from "@tanstack/react-start/server";133134// Basic server handler135const handler = createStartHandler();136137export default {138fetch: handler139};140141// Custom streaming handler142const customHandler = createStartHandler((options) => {143// Custom streaming logic144return new ReadableStream({145start(controller) {146// Custom rendering logic147const html = renderToString(<StartServer router={options.router} />);148controller.enqueue(new TextEncoder().encode(html));149controller.close();150}151});152});153154// Advanced server setup155const handler = createStartHandler(defaultStreamHandler);156157export default {158fetch: async (request, env) => {159// Add custom headers or processing160const response = await handler(request);161response.headers.set("X-Powered-By", "TanStack Start");162return response;163}164};165```166167### Default Stream Handler168169Provides the default streaming implementation for server-side rendering with proper error handling and response streaming.170171```typescript { .api }172/**173* Default streaming handler for SSR with error handling174* @returns StreamHandler that processes render options and returns a stream175*/176function defaultStreamHandler(): StreamHandler;177```178179**Usage Examples:**180181```typescript182import {183createStartHandler,184defaultStreamHandler185} from "@tanstack/react-start/server";186187// Use default streaming188const handler = createStartHandler(defaultStreamHandler());189190// Extend default streaming191const extendedHandler = createStartHandler(192async (options) => {193console.log(`Rendering ${options.request.url}`);194return await defaultStreamHandler()(options);195}196);197```198199### Default Render Handler200201Provides the default rendering implementation for server-side rendering without streaming.202203```typescript { .api }204/**205* Default render handler for non-streaming SSR206* @returns RenderHandler that processes render options and returns HTML207*/208function defaultRenderHandler(): RenderHandler;209210interface RenderHandler {211(renderOptions: RenderOptions): string | Promise<string>;212}213```214215**Usage Examples:**216217```typescript218import { defaultRenderHandler } from "@tanstack/react-start/server";219220// Custom non-streaming handler221const renderHandler = defaultRenderHandler();222223async function customRenderToString(options) {224const html = await renderHandler(options);225return `<!DOCTYPE html><html><body>${html}</body></html>`;226}227```228229### Server Utilities230231Additional server-side utilities for advanced SSR scenarios.232233```typescript { .api }234/**235* Attach server-side SSR utilities to a router instance236* @param router - The router to enhance with SSR capabilities237* @returns Enhanced router with SSR utilities238*/239function attachRouterServerSsrUtils<T extends AnyRouter>(240router: T241): T & ServerSsrUtils;242243/**244* Create a generic request handler with custom configuration245* @param options - Handler configuration options246* @returns Configured request handler247*/248function createRequestHandler<T>(249options: RequestHandlerOptions<T>250): RequestHandler<T>;251252/**253* Define a handler callback for custom server processing254* @param callback - The handler callback function255* @returns Configured handler callback256*/257function defineHandlerCallback<T>(258callback: HandlerCallback<T>259): HandlerCallback<T>;260261/**262* Transform a ReadableStream with router context263* @param stream - The stream to transform264* @param router - Router instance for context265* @returns Transformed stream with router utilities266*/267function transformReadableStreamWithRouter(268stream: ReadableStream,269router: AnyRouter270): ReadableStream;271272/**273* Transform a pipeable stream with router context274* @param stream - The pipeable stream to transform275* @param router - Router instance for context276* @returns Transformed pipeable stream277*/278function transformPipeableStreamWithRouter(279stream: any, // React's PipeableStream type280router: AnyRouter281): any;282```283284### Client Hydration285286Functions for handling client-side hydration and startup processes.287288```typescript { .api }289/**290* Perform client-side hydration of the application291* @returns Promise resolving to the hydrated router instance292*/293function hydrateStart(): Promise<AnyRouter>;294295/**296* Render React Server Components on the client297* @param components - RSC components to render298* @returns Rendered RSC content299*/300function renderRsc(components: any): any;301```302303## Advanced Usage Patterns304305### Custom Server Handler with Middleware306307```typescript308import {309createStartHandler,310defaultStreamHandler311} from "@tanstack/react-start/server";312313const handler = createStartHandler(defaultStreamHandler());314315export default {316fetch: async (request) => {317// Add CORS headers318if (request.method === "OPTIONS") {319return new Response(null, {320status: 204,321headers: {322"Access-Control-Allow-Origin": "*",323"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",324"Access-Control-Allow-Headers": "Content-Type, Authorization"325}326});327}328329const response = await handler(request);330331// Add security headers332response.headers.set("X-Frame-Options", "DENY");333response.headers.set("X-Content-Type-Options", "nosniff");334335return response;336}337};338```339340### Custom Streaming Implementation341342```typescript343import { createStartHandler } from "@tanstack/react-start/server";344import { renderToPipeableStream } from "react-dom/server";345346const customStreamHandler = (options) => {347return new ReadableStream({348start(controller) {349const stream = renderToPipeableStream(350<StartServer router={options.router} />,351{352onShellReady() {353controller.enqueue(new TextEncoder().encode("<!DOCTYPE html>"));354stream.pipe(new WritableStream({355write(chunk) {356controller.enqueue(chunk);357},358close() {359controller.close();360}361}));362},363onError(error) {364console.error("Stream error:", error);365controller.error(error);366}367}368);369}370});371};372373const handler = createStartHandler(customStreamHandler);374```375376## Types377378```typescript { .api }379// Router types from TanStack Router380interface AnyRouter {381state: RouterState;382options: RouterOptions;383history: RouterHistory;384navigate: (options: any) => Promise<void>;385resolveRedirect: (redirect: any) => any;386}387388// Request handler types389interface RequestHandler<TRegister> {390(request: Request): Promise<Response>;391router?: AnyRouter;392}393394interface RequestOptions {395request: Request;396responseHeaders?: Headers;397context?: any;398}399400// Streaming types401interface StreamHandler {402(renderOptions: RenderOptions): ReadableStream | Promise<ReadableStream>;403}404405interface RenderHandler {406(renderOptions: RenderOptions): string | Promise<string>;407}408409interface RenderOptions {410router: AnyRouter;411request: Request;412responseHeaders: Headers;413context?: any;414}415416// Server utilities types417interface ServerSsrUtils {418dehydrate: () => DehydratedRouter;419serialize: (data: any) => string;420deserialize: (data: string) => any;421}422423interface HandlerCallback<T> {424(context: T): Response | Promise<Response>;425}426427interface RequestHandlerOptions<T> {428createRouter: () => AnyRouter;429getRouterContext?: (request: Request) => T;430onError?: (error: Error) => Response;431}432433// Dehydrated state for SSR434interface DehydratedRouter {435state: Record<string, any>;436manifest: Record<string, any>;437context?: any;438}439```440441## Constants442443```typescript { .api }444// HTTP headers used by the SSR system445const HEADERS: {446readonly contentType: "Content-Type";447readonly location: "Location";448readonly cacheControl: "Cache-Control";449};450```