diff --git a/packages/start-client-core/src/client-rpc/createClientRpc.ts b/packages/start-client-core/src/client-rpc/createClientRpc.ts index 0ab3c73e76..4176776bc4 100644 --- a/packages/start-client-core/src/client-rpc/createClientRpc.ts +++ b/packages/start-client-core/src/client-rpc/createClientRpc.ts @@ -4,7 +4,12 @@ import { serverFnFetcher } from './serverFnFetcher' import type { ClientFnMeta } from '../constants' export function createClientRpc(functionId: string) { - const url = process.env.TSS_SERVER_FN_BASE + functionId + const serverFnBase = + (typeof process !== 'undefined' && process.env?.TSS_SERVER_FN_BASE) || + (typeof import.meta !== 'undefined' && + (import.meta as any).env?.TSS_SERVER_FN_BASE) || + '/_serverFn/' + const url = serverFnBase + functionId const serverFnMeta: ClientFnMeta = { id: functionId } const clientFn = (...args: Array) => { diff --git a/packages/start-client-core/tests/createClientRpc.test.ts b/packages/start-client-core/tests/createClientRpc.test.ts new file mode 100644 index 0000000000..e61ddf0f4d --- /dev/null +++ b/packages/start-client-core/tests/createClientRpc.test.ts @@ -0,0 +1,44 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createClientRpc } from '../src/client-rpc/createClientRpc' +import { TSS_SERVER_FUNCTION } from '../src/constants' + +describe('createClientRpc', () => { + const originalEnv = process.env.TSS_SERVER_FN_BASE + + afterEach(() => { + if (originalEnv !== undefined) { + process.env.TSS_SERVER_FN_BASE = originalEnv + } else { + delete process.env.TSS_SERVER_FN_BASE + } + }) + + it('uses process.env.TSS_SERVER_FN_BASE when defined', () => { + process.env.TSS_SERVER_FN_BASE = '/custom-base/' + const rpc = createClientRpc('testFn') + + expect(rpc.url).toBe('/custom-base/testFn') + expect(rpc.serverFnMeta).toEqual({ id: 'testFn' }) + expect(rpc[TSS_SERVER_FUNCTION]).toBe(true) + }) + + it('falls back to default server function base when TSS_SERVER_FN_BASE is undefined', () => { + delete process.env.TSS_SERVER_FN_BASE + const rpc = createClientRpc('testFn') + + expect(rpc.url).toBe('/_serverFn/testFn') + }) + + it('safely falls back without ReferenceError when global process is undefined', () => { + const originalProcess = globalThis.process + try { + // @ts-expect-error simulating browser environment where process is not defined + delete globalThis.process + + const rpc = createClientRpc('testFn') + expect(rpc.url).toBe('/_serverFn/testFn') + } finally { + globalThis.process = originalProcess + } + }) +})