CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tanstack--react-start

Modern full-stack React framework with SSR, streaming, server functions, and API routes powered by TanStack Router and Vite.

Pending
Overview
Eval results
Files

server-functions.mddocs/

Server Functions

Server 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.

Capabilities

Create Server Function

Creates a new server function with configurable HTTP method and middleware support.

/**
 * Creates a server function builder with optional configuration
 * @param options - Configuration options including HTTP method
 * @returns ServerFnBuilder for chaining additional configuration
 */
function createServerFn<TMethod extends Method>(
  options?: { method?: TMethod }
): ServerFnBuilder<{}, TMethod>;

interface ServerFnBuilder<TRegister, TMethod extends Method> {
  /** Define the server-side handler function */
  handler<TResponse>(
    handler: (...args: any[]) => Promise<TResponse> | TResponse
  ): ServerFn<TRegister, TMethod, TResponse>;

  /** Add middleware to the server function */
  middleware<TMiddleware>(
    middleware: TMiddleware
  ): ServerFnBuilder<TRegister & TMiddleware, TMethod>;

  /** Add input validation to the server function */
  inputValidator<TValidator>(
    validator: TValidator
  ): ServerFnBuilder<TRegister & { validator: TValidator }, TMethod>;
}

Usage Examples:

import { createServerFn } from "@tanstack/react-start";

// Basic server function
const getUsers = createServerFn()
  .handler(async () => {
    return await db.user.findMany();
  });

// Server function with POST method
const createUser = createServerFn({ method: 'POST' })
  .handler(async (userData: { name: string; email: string }) => {
    return await db.user.create({ data: userData });
  });

// Server function with validation
const updateUser = createServerFn({ method: 'PUT' })
  .inputValidator((data: unknown) => {
    // Validation logic
    return data as { id: string; name: string };
  })
  .handler(async ({ id, name }) => {
    return await db.user.update({
      where: { id },
      data: { name }
    });
  });

Use Server Function Hook

React hook for calling server functions from client components with automatic redirect handling.

/**
 * Hook for using server functions in React components
 * @param serverFn - The server function to wrap
 * @returns Function that calls the server function with redirect handling
 */
function useServerFn<T extends (...args: any[]) => Promise<any>>(
  serverFn: T
): (...args: Parameters<T>) => ReturnType<T>;

Usage Examples:

import { useServerFn } from "@tanstack/react-start";
import { getUsers, createUser } from "./server-functions";

function UserList() {
  const getUsersFn = useServerFn(getUsers);
  const createUserFn = useServerFn(createUser);
  const [users, setUsers] = useState([]);

  // Load users on mount
  useEffect(() => {
    getUsersFn().then(setUsers);
  }, []);

  // Handle form submission
  const handleSubmit = async (userData) => {
    const newUser = await createUserFn(userData);
    setUsers(prev => [...prev, newUser]);
  };

  return (
    <div>
      {users.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
}

Middleware Application

Apply middleware to server functions for cross-cutting concerns like authentication, logging, and validation.

/**
 * Apply middleware to a server function
 * @param middleware - The middleware to apply
 * @param serverFn - The server function to wrap
 * @returns Enhanced server function with middleware
 */
function applyMiddleware<T>(
  middleware: AnyFunctionMiddleware[],
  serverFn: T
): T;

/**
 * Execute validation logic
 * @param validator - The validator to execute
 * @param input - The input to validate
 * @returns Validated output
 */
function execValidator<T, U>(
  validator: Validator<T, U>,
  input: T
): U;

/**
 * Flatten middleware arrays into a single middleware chain
 * @param middlewares - Array of middleware to flatten
 * @returns Flattened middleware array
 */
function flattenMiddlewares(
  middlewares: AnyFunctionMiddleware[]
): AnyFunctionMiddleware[];

/**
 * Execute a middleware chain
 * @param middlewares - The middleware chain to execute
 * @param context - The execution context
 * @returns Result of middleware execution
 */
function executeMiddleware<T>(
  middlewares: AnyFunctionMiddleware[],
  context: T
): Promise<T>;

Server Function Context

Access server-side context within server functions, including request information and execution environment.

interface ServerFnCtx {
  /** HTTP request object */
  request: Request;
  /** HTTP response headers */
  headers: Headers;
  /** Server-side execution context */
  context: Record<string, any>;
}

Response Utilities

Utilities for creating and manipulating HTTP responses from server functions.

/**
 * Create a JSON response with proper headers
 * @param data - The data to serialize as JSON
 * @param options - Response options including status and headers
 * @returns JSON response object
 */
function json<T>(
  data: T,
  options?: {
    status?: number;
    headers?: HeadersInit;
  }
): JsonResponse;

/**
 * Merge multiple header objects into one
 * @param headers - Array of header objects to merge
 * @returns Merged headers object
 */
function mergeHeaders(...headers: HeadersInit[]): Headers;

/**
 * Perform client-side hydration of server state
 * @param router - The router instance to hydrate
 * @returns Promise resolving to hydrated router
 */
function hydrate<T>(router: T): Promise<T>;

Types

// HTTP methods supported by server functions
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

// Server function interface
interface ServerFn<TRegister, TMethod extends Method, TResponse> {
  (...args: any[]): Promise<TResponse>;
  url: string;
  functionId: string;
  method: TMethod;
}

// Server function context
interface ServerFnCtx {
  request: Request;
  headers: Headers;
  context: Record<string, any>;
}

// Middleware function type
interface MiddlewareFn<TInput, TOutput> {
  (input: TInput, context: ServerFnCtx): Promise<TOutput> | TOutput;
}

// Server function builder options
interface ServerFnBaseOptions<TRegister, TMethod, TResponse, TMiddlewares, TInputValidator> {
  method?: TMethod;
  middleware?: TMiddlewares;
  inputValidator?: TInputValidator;
  handler?: (...args: any[]) => Promise<TResponse> | TResponse;
}

// Fetcher configuration for server functions
interface CompiledFetcherFnOptions {
  method: Method;
  headers?: HeadersInit;
  body?: BodyInit;
}

interface CompiledFetcherFn {
  (url: string, options: CompiledFetcherFnOptions): Promise<Response>;
}

interface Fetcher {
  fn: CompiledFetcherFn;
  options: CompiledFetcherFnOptions;
}

// JSON response type
interface JsonResponse {
  json(): any;
  status: number;
  headers: Headers;
  ok: boolean;
  statusText: string;
}

// Dehydrated router state for SSR
interface DehydratedRouter {
  state: Record<string, any>;
  manifest: Record<string, any>;
}

Constants

// Server function markers and headers
const TSS_SERVER_FUNCTION: unique symbol;
const TSS_FORMDATA_CONTEXT: string;
const X_TSS_SERIALIZED: string;

Install with Tessl CLI

npx tessl i tessl/npm-tanstack--react-start

docs

index.md

isomorphic-functions.md

middleware.md

request-response.md

rpc-system.md

server-functions.md

server-utilities.md

ssr-components.md

vite-plugin.md

tile.json