- 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
server-functions.md docs/
1# Server Functions23Server functions are type-safe functions that run on the server but can be called from the client as if they were regular functions. They enable seamless client-server communication with automatic serialization, validation, and error handling.45## Capabilities67### Create Server Function89Creates a new server function with configurable HTTP method and middleware support.1011```typescript { .api }12/**13* Creates a server function builder with optional configuration14* @param options - Configuration options including HTTP method15* @returns ServerFnBuilder for chaining additional configuration16*/17function createServerFn<TMethod extends Method>(18options?: { method?: TMethod }19): ServerFnBuilder<{}, TMethod>;2021interface ServerFnBuilder<TRegister, TMethod extends Method> {22/** Define the server-side handler function */23handler<TResponse>(24handler: (...args: any[]) => Promise<TResponse> | TResponse25): ServerFn<TRegister, TMethod, TResponse>;2627/** Add middleware to the server function */28middleware<TMiddleware>(29middleware: TMiddleware30): ServerFnBuilder<TRegister & TMiddleware, TMethod>;3132/** Add input validation to the server function */33inputValidator<TValidator>(34validator: TValidator35): ServerFnBuilder<TRegister & { validator: TValidator }, TMethod>;36}37```3839**Usage Examples:**4041```typescript42import { createServerFn } from "@tanstack/react-start";4344// Basic server function45const getUsers = createServerFn()46.handler(async () => {47return await db.user.findMany();48});4950// Server function with POST method51const createUser = createServerFn({ method: 'POST' })52.handler(async (userData: { name: string; email: string }) => {53return await db.user.create({ data: userData });54});5556// Server function with validation57const updateUser = createServerFn({ method: 'PUT' })58.inputValidator((data: unknown) => {59// Validation logic60return data as { id: string; name: string };61})62.handler(async ({ id, name }) => {63return await db.user.update({64where: { id },65data: { name }66});67});68```6970### Use Server Function Hook7172React hook for calling server functions from client components with automatic redirect handling.7374```typescript { .api }75/**76* Hook for using server functions in React components77* @param serverFn - The server function to wrap78* @returns Function that calls the server function with redirect handling79*/80function useServerFn<T extends (...args: any[]) => Promise<any>>(81serverFn: T82): (...args: Parameters<T>) => ReturnType<T>;83```8485**Usage Examples:**8687```typescript88import { useServerFn } from "@tanstack/react-start";89import { getUsers, createUser } from "./server-functions";9091function UserList() {92const getUsersFn = useServerFn(getUsers);93const createUserFn = useServerFn(createUser);94const [users, setUsers] = useState([]);9596// Load users on mount97useEffect(() => {98getUsersFn().then(setUsers);99}, []);100101// Handle form submission102const handleSubmit = async (userData) => {103const newUser = await createUserFn(userData);104setUsers(prev => [...prev, newUser]);105};106107return (108<div>109{users.map(user => (110<div key={user.id}>{user.name}</div>111))}112</div>113);114}115```116117### Middleware Application118119Apply middleware to server functions for cross-cutting concerns like authentication, logging, and validation.120121```typescript { .api }122/**123* Apply middleware to a server function124* @param middleware - The middleware to apply125* @param serverFn - The server function to wrap126* @returns Enhanced server function with middleware127*/128function applyMiddleware<T>(129middleware: AnyFunctionMiddleware[],130serverFn: T131): T;132133/**134* Execute validation logic135* @param validator - The validator to execute136* @param input - The input to validate137* @returns Validated output138*/139function execValidator<T, U>(140validator: Validator<T, U>,141input: T142): U;143144/**145* Flatten middleware arrays into a single middleware chain146* @param middlewares - Array of middleware to flatten147* @returns Flattened middleware array148*/149function flattenMiddlewares(150middlewares: AnyFunctionMiddleware[]151): AnyFunctionMiddleware[];152153/**154* Execute a middleware chain155* @param middlewares - The middleware chain to execute156* @param context - The execution context157* @returns Result of middleware execution158*/159function executeMiddleware<T>(160middlewares: AnyFunctionMiddleware[],161context: T162): Promise<T>;163```164165### Server Function Context166167Access server-side context within server functions, including request information and execution environment.168169```typescript { .api }170interface ServerFnCtx {171/** HTTP request object */172request: Request;173/** HTTP response headers */174headers: Headers;175/** Server-side execution context */176context: Record<string, any>;177}178```179180### Response Utilities181182Utilities for creating and manipulating HTTP responses from server functions.183184```typescript { .api }185/**186* Create a JSON response with proper headers187* @param data - The data to serialize as JSON188* @param options - Response options including status and headers189* @returns JSON response object190*/191function json<T>(192data: T,193options?: {194status?: number;195headers?: HeadersInit;196}197): JsonResponse;198199/**200* Merge multiple header objects into one201* @param headers - Array of header objects to merge202* @returns Merged headers object203*/204function mergeHeaders(...headers: HeadersInit[]): Headers;205206/**207* Perform client-side hydration of server state208* @param router - The router instance to hydrate209* @returns Promise resolving to hydrated router210*/211function hydrate<T>(router: T): Promise<T>;212```213214## Types215216```typescript { .api }217// HTTP methods supported by server functions218type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';219220// Server function interface221interface ServerFn<TRegister, TMethod extends Method, TResponse> {222(...args: any[]): Promise<TResponse>;223url: string;224functionId: string;225method: TMethod;226}227228// Server function context229interface ServerFnCtx {230request: Request;231headers: Headers;232context: Record<string, any>;233}234235// Middleware function type236interface MiddlewareFn<TInput, TOutput> {237(input: TInput, context: ServerFnCtx): Promise<TOutput> | TOutput;238}239240// Server function builder options241interface ServerFnBaseOptions<TRegister, TMethod, TResponse, TMiddlewares, TInputValidator> {242method?: TMethod;243middleware?: TMiddlewares;244inputValidator?: TInputValidator;245handler?: (...args: any[]) => Promise<TResponse> | TResponse;246}247248// Fetcher configuration for server functions249interface CompiledFetcherFnOptions {250method: Method;251headers?: HeadersInit;252body?: BodyInit;253}254255interface CompiledFetcherFn {256(url: string, options: CompiledFetcherFnOptions): Promise<Response>;257}258259interface Fetcher {260fn: CompiledFetcherFn;261options: CompiledFetcherFnOptions;262}263264// JSON response type265interface JsonResponse {266json(): any;267status: number;268headers: Headers;269ok: boolean;270statusText: string;271}272273// Dehydrated router state for SSR274interface DehydratedRouter {275state: Record<string, any>;276manifest: Record<string, any>;277}278```279280## Constants281282```typescript { .api }283// Server function markers and headers284const TSS_SERVER_FUNCTION: unique symbol;285const TSS_FORMDATA_CONTEXT: string;286const X_TSS_SERIALIZED: string;287```