- Spec files
npm-tanstack--react-start
Describes: pkg:npm/@tanstack/react-start@1.131.x
- Description
- SSR, Streaming, Server Functions, API Routes, bundling and more powered by TanStack Router and Vite. Ready to deploy to your favorite hosting provider.
- Author
- tessl
- Last updated
How to use
npx @tessl/cli registry install tessl/npm-tanstack--react-start@1.131.0
client.md docs/
1# Client-Side Framework23Client-side functionality for TanStack React Start, including the main application component, hooks for server function integration, and utilities for handling full-stack React applications with hydration and routing.45## Capabilities67### StartClient Component89Main client-side application component that handles hydration and provides the router context for React applications.1011```typescript { .api }12/**13* Main client-side application component for TanStack Start14* Handles hydration of server-rendered content and provides router context15* @param props - Component props containing the router instance16* @returns JSX element with router provider and hydration handling17*/18function StartClient(props: { router: AnyRouter }): JSX.Element;19```2021**Usage Example:**2223```typescript24import { StartClient } from '@tanstack/react-start';25import { createRouter } from './router';2627const router = createRouter();2829function App() {30return <StartClient router={router} />;31}32```3334### useServerFn Hook3536React hook for calling server functions with automatic router integration and redirect handling.3738```typescript { .api }39/**40* Hook for calling server functions with router integration41* Automatically handles redirects and router state updates42* @param serverFn - Server function to wrap43* @returns Function that calls the server function with redirect handling44*/45function useServerFn<T extends (...deps: Array<any>) => Promise<any>>(46serverFn: T47): (...args: Parameters<T>) => ReturnType<T>;48```4950**Usage Examples:**5152```typescript53import { useServerFn, createServerFn } from '@tanstack/react-start';5455// Define server function56const getUserData = createServerFn().handler(async (userId: string) => {57return await database.getUser(userId);58});5960// Use in component61function UserProfile({ userId }: { userId: string }) {62const fetchUser = useServerFn(getUserData);63const [user, setUser] = useState(null);6465const loadUser = async () => {66try {67const userData = await fetchUser(userId);68setUser(userData);69} catch (error) {70console.error('Failed to load user:', error);71}72};7374return (75<div>76<button onClick={loadUser}>Load User</button>77{user && <div>{user.name}</div>}78</div>79);80}81```8283### Server Function Creation8485Core functionality for creating server functions that can be called from client-side code.8687```typescript { .api }88/**89* Creates a server function that can be called from client-side code90* @param options - Optional configuration for the server function91* @returns Server function builder for chaining configuration92*/93function createServerFn<TValidator = undefined, TMiddleware = []>(94options?: ServerFnBaseOptions<TValidator, TMiddleware>95): ServerFnBuilder<TValidator, TMiddleware>;9697interface ServerFnBuilder<TValidator, TMiddleware> {98/** Configure HTTP method for the server function */99method<TMethod extends Method>(method: TMethod): ServerFnBuilder<TValidator, TMiddleware>;100/** Add validation to the server function */101validator<V>(validator: V): ServerFnBuilder<V, TMiddleware>;102/** Add middleware to the server function */103middleware<M>(middleware: M): ServerFnBuilder<TValidator, M>;104/** Define the handler function that runs on the server */105handler<THandlerFn extends Function>(handlerFn: THandlerFn): CompiledFetcherFn<THandlerFn>;106}107108interface ServerFnBaseOptions<TValidator, TMiddleware> {109method?: Method;110validator?: TValidator;111middleware?: TMiddleware;112}113114type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';115```116117### Isomorphic Functions118119Functions that can run on both client and server environments with different implementations.120121```typescript { .api }122/**123* Creates a function that works on both client and server with different implementations124* @param clientFn - Function to run on the client125* @param serverFn - Function to run on the server126* @returns Isomorphic function that automatically chooses the correct implementation127*/128function createIsomorphicFn<TArgs extends Array<any>, TReturn>(129clientFn: (...args: TArgs) => TReturn,130serverFn: (...args: TArgs) => TReturn131): IsomorphicFn<TArgs, TReturn>;132133interface IsomorphicFn<TArgs extends Array<any>, TReturn> {134(...args: TArgs): TReturn;135}136```137138### Environment-Specific Functions139140Utilities for marking functions as client-only or server-only.141142```typescript { .api }143/**144* Marks a function as server-only, throwing an error if called on client145* @param fn - Function that should only run on the server146* @returns Server-only function wrapper147*/148function serverOnly<T extends Function>(fn: T): ServerOnlyFn<T>;149150/**151* Marks a function as client-only, throwing an error if called on server152* @param fn - Function that should only run on the client153* @returns Client-only function wrapper154*/155function clientOnly<T extends Function>(fn: T): ClientOnlyFn<T>;156157interface ServerOnlyFn<T extends Function> extends Function {158(): never; // Throws error on client159}160161interface ClientOnlyFn<T extends Function> extends Function {162(): never; // Throws error on server163}164```165166### Middleware System167168Middleware creation and management for server functions.169170```typescript { .api }171/**172* Creates middleware for server functions173* @param options - Middleware configuration options174* @returns Configured middleware function175*/176function createMiddleware<TOptions extends FunctionMiddlewareOptions>(177options: TOptions178): FunctionMiddlewareWithTypes<TOptions>;179180/**181* Registers middleware globally for all server functions182* @param middleware - Middleware function to register globally183*/184function registerGlobalMiddleware(middleware: AnyFunctionMiddleware): void;185186/** Global middleware registry */187const globalMiddleware: Array<AnyFunctionMiddleware>;188189interface FunctionMiddlewareOptions {190validator?: any;191server?: Function;192client?: Function;193after?: Function;194}195196interface FunctionMiddlewareWithTypes<TOptions> {197validator: TOptions['validator'];198server: TOptions['server'];199client: TOptions['client'];200after: TOptions['after'];201}202203type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<any>;204```205206### Utility Functions207208Core utility functions for data handling and serialization.209210```typescript { .api }211/**212* Creates a JSON response with proper headers213* @param data - Data to serialize as JSON214* @param init - Optional response initialization options215* @returns Response object with JSON content216*/217function json<T = any>(data: T, init?: ResponseInit): JsonResponse<T>;218219/**220* Merges multiple headers objects or Headers instances221* @param headers - Headers to merge222* @returns Merged Headers object223*/224function mergeHeaders(...headers: Array<HeadersInit | undefined>): Headers;225226/**227* Hydrates client-side router with server-rendered data228* @param router - Router instance to hydrate229* @returns Promise that resolves when hydration is complete230*/231function hydrate(router: AnyRouter): Promise<void | Array<Array<void>>>;232233interface JsonResponse<T = any> extends Response {234json(): Promise<T>;235}236```237238### Serialization239240Custom serialization system for complex data transfer between client and server.241242```typescript { .api }243/** Start framework serializer for handling complex data types */244const startSerializer: StartSerializer;245246interface StartSerializer {247stringify: SerializerStringify;248parse: SerializerParse;249stringifyBy: SerializerStringifyBy;250parseBy: SerializerParseBy;251}252253interface SerializerStringify {254(value: Serializable): string;255}256257interface SerializerParse {258(value: string): Serializable;259}260261interface SerializerStringifyBy {262(key: string, value: Serializable): string;263}264265interface SerializerParseBy {266(key: string, value: string): Serializable;267}268269type Serializable =270| string271| number272| boolean273| null274| undefined275| Date276| RegExp277| Array<Serializable>278| { [key: string]: Serializable };279280interface SerializerExtensions {281ReadableStream: React.JSX.Element;282}283```284285### React Server Components (Experimental)286287Experimental support for React Server Components.288289```typescript { .api }290/**291* Renders React Server Components (experimental feature)292* @param input - RSC input data or stream293* @returns JSX element from server component294*/295function renderRsc(input: any): React.JSX.Element;296```297298### Deprecated Components299300Legacy components maintained for backwards compatibility.301302```typescript { .api }303/**304* @deprecated Use HeadContent from @tanstack/react-router instead305* Legacy Meta component for head content management306*/307function Meta(): JSX.Element;308309/**310* @deprecated Moved to @tanstack/react-router as Scripts component311* Legacy Scripts component for script injection312*/313function Scripts(): JSX.Element;314```315316## Core Types317318```typescript { .api }319interface AnyRouter {320state: {321matches: Array<any>;322location: any;323};324navigate: (options: any) => Promise<any>;325resolveRedirect: (redirect: any) => { options: any };326}327328interface CompiledFetcherFn<THandlerFn> extends Function {329(...args: Parameters<THandlerFn>): Promise<ReturnType<THandlerFn>>;330url: string;331functionId: string;332}333334interface DehydratedRouter {335dehydratedMatches: Array<any>;336[key: string]: any;337}338339interface FetcherData<T = any> {340data: T;341error?: Error;342isLoading: boolean;343}344345interface ServerFnCtx {346request: Request;347params: Record<string, string>;348data: FormData | any;349}350351type ServerFnResponseType = Response | any;352353interface RscStream extends ReadableStream {354[Symbol.toStringTag]: 'RscStream';355}356357// Middleware types358interface FunctionMiddlewareClientFnOptions<TValidator, TContext> {359validator: TValidator;360context: TContext;361next: FunctionMiddlewareClientNextFn;362}363364interface FunctionMiddlewareClientFnResult<TResult, TContext> {365result: TResult;366context: TContext;367}368369interface FunctionMiddlewareClientNextFn {370(): Promise<any>;371}372373interface FunctionClientResultWithContext<TResult, TContext> {374result: TResult;375context: TContext;376}377378interface FunctionMiddlewareServerFnOptions<TValidator, TContext> {379validator: TValidator;380context: TContext;381next: FunctionMiddlewareServerNextFn;382}383384interface FunctionMiddlewareServerFnResult<TResult, TContext> {385result: TResult;386context: TContext;387}388389interface FunctionMiddlewareServerNextFn {390(): Promise<any>;391}392393interface FunctionServerResultWithContext<TResult, TContext> {394result: TResult;395context: TContext;396}397```