Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/swift-radios-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/start-plugin-core': patch
---

Compile `createServerOnlyFn`, `createClientOnlyFn` and `createIsomorphicFn` calls before server functions and middleware, so they are transformed when passed directly to `.handler()` or nested inside a handler body.
23 changes: 20 additions & 3 deletions e2e/react-start/server-functions/src/routes/env-only.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ const testOnServer = createServerFn().handler(() => {
return { serverOnServer, clientOnServer }
})

// Env-only fn passed directly as the handler, see #8446
const inlineServerOnly = createServerFn().handler(
createServerOnlyFn(() => 'inline server-only handler ran'),
)

export const Route = createFileRoute('/env-only')({
component: RouteComponent,
})
Expand All @@ -30,7 +35,8 @@ function RouteComponent() {
const [results, setResults] = useState<Partial<Record<string, string>>>()

async function handleClick() {
const { serverOnServer, clientOnServer } = await testOnServer()
const [{ serverOnServer, clientOnServer }, inlineServerOnlyResult] =
await Promise.all([testOnServer(), inlineServerOnly()])
const clientOnClient = clientEcho('hello')
let serverOnClient: string
try {
Expand All @@ -45,11 +51,17 @@ function RouteComponent() {
clientOnServer,
clientOnClient,
serverOnClient,
inlineServerOnlyResult,
})
}

const { serverOnServer, clientOnServer, clientOnClient, serverOnClient } =
results || {}
const {
serverOnServer,
clientOnServer,
clientOnClient,
serverOnClient,
inlineServerOnlyResult,
} = results || {}

return (
<div>
Expand All @@ -73,6 +85,11 @@ function RouteComponent() {
<pre data-testid="client-on-server">{clientOnServer}</pre>
When we called the function on the client:
<pre data-testid="client-on-client">{clientOnClient}</pre>
<br />
<h1>
<code>inlineServerOnly</code>
</h1>
<pre data-testid="inline-server-only">{inlineServerOnlyResult}</pre>
</div>
)}
</div>
Expand Down
22 changes: 19 additions & 3 deletions e2e/react-start/server-functions/src/routes/isomorphic-fns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ const getServerEcho = createServerFn()
.validator((input: string) => input)
.handler(({ data }) => getEcho(data))

// Isomorphic fn passed directly as the handler, see #8446
const getInlineIsomorphic = createServerFn().handler(
createIsomorphicFn()
.server(() => 'server')
.client(() => 'client'),
)

export const Route = createFileRoute('/isomorphic-fns')({
component: RouteComponent,
loader() {
Expand All @@ -31,13 +38,15 @@ function RouteComponent() {
async function handleClick() {
const envOnClick = getEnv()
const echo = getEcho('hello')
const [serverEnv, serverEcho] = await Promise.all([
const [serverEnv, serverEcho, inlineIsomorphic] = await Promise.all([
getServerEnv(),
getServerEcho({ data: 'hello' }),
getInlineIsomorphic(),
])
setResults({ envOnClick, echo, serverEnv, serverEcho })
setResults({ envOnClick, echo, serverEnv, serverEcho, inlineIsomorphic })
}
const { envOnClick, echo, serverEnv, serverEcho } = results || {}
const { envOnClick, echo, serverEnv, serverEcho, inlineIsomorphic } =
results || {}
return (
<div>
<button onClick={handleClick} data-testid="test-isomorphic-results-btn">
Expand All @@ -64,6 +73,13 @@ function RouteComponent() {
</pre>
When we called the function on the client it returned:
<pre data-testid="client-echo-result">{JSON.stringify(echo)}</pre>
<br />
<h1>
<code>getInlineIsomorphic</code>
</h1>
<pre data-testid="inline-isomorphic-result">
{JSON.stringify(inlineIsomorphic)}
</pre>
</div>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ test('isomorphic functions can have different implementations on client and serv
await expect(page.getByTestId('client-echo-result')).toContainText(
'client received hello',
)
await expect(page.getByTestId('inline-isomorphic-result')).toContainText(
'server',
)
})

test('env-only functions can only be called on the server or client respectively', async ({
Expand All @@ -148,6 +151,9 @@ test('env-only functions can only be called on the server or client respectively
await expect(page.getByTestId('client-on-client')).toContainText(
'client got: hello',
)
await expect(page.getByTestId('inline-server-only')).toContainText(
'inline server-only handler ran',
)
})

test('Server function can return null for GET and POST calls', async ({
Expand Down
4 changes: 3 additions & 1 deletion packages/start-plugin-core/src/start-compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,11 @@ const BuiltInKindHandlers: Record<
// ClientOnlyJSX is handled separately via JSX traversal, not here
}

// In-place rewrites run first: ServerFn and Middleware replace or clone whole
// subtrees, which would leave nested candidates pointing at detached nodes.
const BuiltInKindHandlerOrder: Array<
Exclude<BuiltInLookupKind, 'ClientOnlyJSX'>
> = ['ServerFn', 'Middleware', 'IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn']
> = ['IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn', 'ServerFn', 'Middleware']

// All lookup kinds as an array for iteration with proper typing
const AllBuiltInLookupKinds = Object.keys(
Expand Down
49 changes: 49 additions & 0 deletions packages/start-plugin-core/tests/compiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1266,3 +1266,52 @@ describe('re-export chain resolution', () => {
expect(updatedResult!.code).not.toContain('server-only-value')
})
})

describe('env-only and isomorphic fns nested in createServerFn().handler()', () => {
// https://github.com/TanStack/router/issues/8446
const code = `
import { createServerFn, createServerOnlyFn, createClientOnlyFn, createIsomorphicFn } from '@tanstack/react-start'

export const inlineServerOnly = createServerFn().handler(createServerOnlyFn(() => 'server-only-impl'))
export const inlineIsomorphic = createServerFn().handler(
createIsomorphicFn().server(() => 'server-impl').client(() => 'client-impl'),
)
export const nestedClientOnly = createServerFn().handler(() => {
const readWindow = createClientOnlyFn(() => window.innerWidth)
return 'nested-impl'
})
`

test.each([
{ env: 'client', rpc: 'createClientRpc(' },
{ env: 'server', rpc: 'createSsrRpc(' },
] as const)(
'$env caller replaces every handler with an RPC stub',
async ({ env, rpc }) => {
const compiler = createFullCompiler(env)
const result = await compiler.compile({ code, id: '/test/src/test.ts' })

expect(result!.code.split(rpc)).toHaveLength(4)
expect(result!.code).not.toContain('-impl')
expect(result!.code).not.toContain('.handler("')
},
)

test('server provider keeps the server implementation of each handler', async () => {
const compiler = createFullCompiler('server')
const result = await compiler.compile({
code,
id: '/test/src/test.ts?tss-serverfn-split',
})

expect(result!.code).toContain("'server-only-impl'")
expect(result!.code).toContain("'server-impl'")
expect(result!.code).not.toContain("'client-impl'")
expect(result!.code).toContain(
'createClientOnlyFn() functions can only be called on the client!',
)
expect(result!.code).not.toMatch(
/create(ServerOnly|ClientOnly|Isomorphic)Fn\((?!\))/,
)
})
})