- 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
isomorphic-functions.md docs/
1# Isomorphic Functions23Isomorphic functions allow you to create functions with different implementations for client and server environments. This enables code that adapts to its execution context, providing optimal behavior on both sides of your application.45## Capabilities67### Create Isomorphic Function89Creates a function that can have different implementations on the client and server, with implementations defaulting to no-op functions when not provided.1011```typescript { .api }12/**13* Creates an isomorphic function with different client/server implementations14* @returns IsomorphicFnBase for chaining client/server implementations15*/16function createIsomorphicFn(): IsomorphicFnBase;1718interface IsomorphicFnBase {19/** Define the server-side implementation */20server<TArgs extends Array<any>, TServer>(21serverImpl: (...args: TArgs) => TServer22): ServerOnlyFn<TArgs, TServer>;2324/** Define the client-side implementation */25client<TArgs extends Array<any>, TClient>(26clientImpl: (...args: TArgs) => TClient27): ClientOnlyFn<TArgs, TClient>;28}29```3031**Usage Examples:**3233```typescript34import { createIsomorphicFn } from "@tanstack/react-start";3536// Logging function with different implementations37const log = createIsomorphicFn()38.server((message: string) => {39// Server-side: log to console with timestamp40console.log(`[${new Date().toISOString()}] ${message}`);41})42.client((message: string) => {43// Client-side: log to browser console44console.log(`[CLIENT] ${message}`);45});4647// Storage function with different backends48const getItem = createIsomorphicFn()49.server((key: string) => {50// Server-side: use environment variables or file system51return process.env[key] || null;52})53.client((key: string) => {54// Client-side: use localStorage55return localStorage.getItem(key);56});57```5859### Create Server-Only Function6061Creates a function that only executes on the server, with the option to add a client-side implementation later.6263```typescript { .api }64/**65* Creates a server-only function with optional client implementation66* @param serverImpl - The server-side implementation67* @returns ServerOnlyFn that can be extended with client implementation68*/69function createServerOnlyFn<TArgs extends Array<any>, TServer>(70serverImpl: (...args: TArgs) => TServer71): ServerOnlyFn<TArgs, TServer>;7273interface ServerOnlyFn<TArgs extends Array<any>, TServer>74extends IsomorphicFn<TArgs, TServer> {75/** Add a client-side implementation */76client<TClient>(77clientImpl: (...args: TArgs) => TClient78): IsomorphicFn<TArgs, TServer, TClient>;79}80```8182**Usage Examples:**8384```typescript85import { createServerOnlyFn } from "@tanstack/react-start";8687// Database access function (server-only by default)88const getUser = createServerOnlyFn((id: string) => {89// Server-side: access database90return db.user.findUnique({ where: { id } });91});9293// Add client-side fallback94const getUserWithFallback = createServerOnlyFn((id: string) => {95return db.user.findUnique({ where: { id } });96}).client((id: string) => {97// Client-side: fetch from API98return fetch(`/api/users/${id}`).then(r => r.json());99});100```101102### Create Client-Only Function103104Creates a function that only executes on the client, with the option to add a server-side implementation later.105106```typescript { .api }107/**108* Creates a client-only function with optional server implementation109* @param clientImpl - The client-side implementation110* @returns ClientOnlyFn that can be extended with server implementation111*/112function createClientOnlyFn<TArgs extends Array<any>, TClient>(113clientImpl: (...args: TArgs) => TClient114): ClientOnlyFn<TArgs, TClient>;115116interface ClientOnlyFn<TArgs extends Array<any>, TClient>117extends IsomorphicFn<TArgs, undefined, TClient> {118/** Add a server-side implementation */119server<TServer>(120serverImpl: (...args: TArgs) => TServer121): IsomorphicFn<TArgs, TServer, TClient>;122}123```124125**Usage Examples:**126127```typescript128import { createClientOnlyFn } from "@tanstack/react-start";129130// Analytics tracking function (client-only by default)131const trackEvent = createClientOnlyFn((event: string, data: any) => {132// Client-side: send to analytics service133analytics.track(event, data);134});135136// Add server-side implementation for SSR contexts137const trackEventWithServer = createClientOnlyFn((event: string, data: any) => {138analytics.track(event, data);139}).server((event: string, data: any) => {140// Server-side: log for debugging or send to server analytics141console.log(`[ANALYTICS] ${event}:`, data);142});143```144145## Advanced Usage Patterns146147### Environment Detection148149Isomorphic functions automatically detect their execution environment and call the appropriate implementation:150151```typescript152import { createIsomorphicFn } from "@tanstack/react-start";153154const getCurrentUrl = createIsomorphicFn()155.server(() => {156// Server-side: construct URL from request157return `${process.env.BASE_URL}/current-page`;158})159.client(() => {160// Client-side: use window.location161return window.location.href;162});163164// This will call the appropriate implementation based on context165const url = getCurrentUrl();166```167168### Shared Logic with Environment-Specific Details169170```typescript171import { createIsomorphicFn } from "@tanstack/react-start";172173const formatDate = createIsomorphicFn()174.server((date: Date) => {175// Server-side: use server timezone176return date.toLocaleString('en-US', {177timeZone: process.env.SERVER_TIMEZONE || 'UTC'178});179})180.client((date: Date) => {181// Client-side: use user's timezone182return date.toLocaleString();183});184```185186## Types187188```typescript { .api }189// Base isomorphic function type190interface IsomorphicFn<191TArgs extends Array<any> = [],192TServer = undefined,193TClient = undefined194> {195(...args: TArgs): TServer | TClient;196}197198// Server-only function with optional client extension199interface ServerOnlyFn<TArgs extends Array<any>, TServer>200extends IsomorphicFn<TArgs, TServer> {201client<TClient>(202clientImpl: (...args: TArgs) => TClient203): IsomorphicFn<TArgs, TServer, TClient>;204}205206// Client-only function with optional server extension207interface ClientOnlyFn<TArgs extends Array<any>, TClient>208extends IsomorphicFn<TArgs, undefined, TClient> {209server<TServer>(210serverImpl: (...args: TArgs) => TServer211): IsomorphicFn<TArgs, TServer, TClient>;212}213214// Base interface for creating isomorphic functions215interface IsomorphicFnBase extends IsomorphicFn {216server<TArgs extends Array<any>, TServer>(217serverImpl: (...args: TArgs) => TServer218): ServerOnlyFn<TArgs, TServer>;219220client<TArgs extends Array<any>, TClient>(221clientImpl: (...args: TArgs) => TClient222): ClientOnlyFn<TArgs, TClient>;223}224```