Skip to content
7 changes: 7 additions & 0 deletions .changeset/start-server-fn-custom-id-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/start-plugin-core': minor
---

A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called.

Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle.
4 changes: 3 additions & 1 deletion docs/start/framework/react/guide/server-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,9 @@ Customization:

You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.

Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
Return `undefined` (or an empty string) to use the default ID. Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.

The ID becomes one segment of the server function's URL (`/_serverFn/<id>`), unencoded, so use only ASCII letters, digits, `-`, `.`, `_`, `~` and `$`, and not `.` or `..`. An ID with whitespace, a control or non-ASCII character, or any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{` and `}`, an ID that is `.` or `..`, or one with a percent-encoding the server reads as another ID (`%41` for `A`, lowercase hex, `%2E`) or rejects, fails the build with an error naming the file, the function and the ID: the request would reach another function or none. Other characters (`%`, `+`, `:`, `;`, `@`, `'`, `|`, `[`, `]`, …) still work, with a deprecation warning: the next major version rejects them, since proxies and servers may encode or normalise them in the URL. `filename` contains `/`, so hash it (as in the example below) rather than embedding it as is.

Please note that this customization is **experimental** and subject to change.

Expand Down
39 changes: 31 additions & 8 deletions packages/start-plugin-core/src/start-compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { handleCreateIsomorphicFn } from './handleCreateIsomorphicFn'
import { handleEnvOnlyFn } from './handleEnvOnly'
import { handleClientOnlyJSX } from './handleClientOnlyJSX'
import { cleanId } from './utils'
import {
customIdCheck,
customIdError,
customIdWarning,
} from './server-fn-id-check'
import type {
CompilationContext,
DevServerFnModuleSpecifierEncoder,
Expand Down Expand Up @@ -631,11 +636,15 @@ export class StartCompiler {
* In dev mode, uses a base64-encoded JSON with file path and export name.
* In build mode, uses SHA256 hash or custom generator.
*/
private generateFunctionId(opts: {
filename: string
functionName: string
extractedFilename: string
}): string {
private generateFunctionId(
opts: {
filename: string
functionName: string
variableName: string
extractedFilename: string
},
warn: ((message: string) => void) | undefined,
): string {
if (this.mode === 'dev') {
// In dev, encode the file path and export name for direct lookup.
// Each bundler adapter supplies its own strategy for encoding
Expand Down Expand Up @@ -673,11 +682,25 @@ export class StartCompiler {
functionId = knownFn.functionId
}

if (this.options.generateFunctionId) {
functionId ??= this.options.generateFunctionId({
if (functionId === undefined && this.options.generateFunctionId) {
functionId = this.options.generateFunctionId({
filename: opts.filename,
functionName: opts.functionName,
})
if (functionId) {
const subject = {
name: opts.variableName,
functionName: opts.functionName,
rootRel: opts.filename,
}
const check = customIdCheck(functionId)
if (check === 'error') {
throw new Error(customIdError(subject, functionId))
}
if (check === 'deprecated') {
warn?.(customIdWarning(subject, functionId))
}
}
}
if (!functionId) {
functionId = crypto.createHash('sha256').update(entryId).digest('hex')
Expand Down Expand Up @@ -1400,7 +1423,7 @@ export class StartCompiler {
})(),
warn: warnFn,

generateFunctionId: (opts) => this.generateFunctionId(opts),
generateFunctionId: (opts) => this.generateFunctionId(opts, warnFn),
getKnownServerFns: this.options.getKnownServerFns,
serverFnProviderModuleDirectives:
this.options.serverFnProviderModuleDirectives,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export function handleCreateServerFn(
const functionId = context.generateFunctionId({
filename: relativeFilename,
functionName,
variableName: existingVariableName,
extractedFilename,
})

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Which ids a custom `serverFns.generateFunctionId` may return. The client
* puts the id after `TSS_SERVER_FN_BASE` unencoded and the server reads that
* path segment back, so an id has to survive that trip whole.
*/

interface CustomIdSubject {
/** The server function's variable name. */
name: string
/** The `functionName` the generator received. */
functionName: string
/** The defining file, relative to the root. */
rootRel: string
}

/**
* `error`: the id never reached its handler: a character that splits or
* ends the path or that a client percent-encodes, a dot segment, which URL
* parsing removes, or a percent-encoding the server decodes to another id
* or rejects (`readBack`). `deprecated`: an ASCII character outside RFC
* 3986's unreserved set and `$`, which reaches the server but which proxies
* and servers may encode or normalise.
*/
export function customIdCheck(id: string): 'ok' | 'deprecated' | 'error' {
if (
id === '.' ||
id === '..' ||
/[^\x21-\x7e]|["#/<>?\\^`{}]/.test(id) ||
(id.includes('%') && readBack(id) !== id)
) {
return 'error'
}
return /^[A-Za-z0-9\-._~$]+$/.test(id) ? 'ok' : 'deprecated'
}

/**
* The id the server reads from the URL of an id holding `%`: the request
* URL's path, decoded as Start's server does when the path holds `%`
* (router-core `getNormalizedURL`, `decodePath`: `decodeURI` keeping `%25`
* and `%5C`, then control characters and `"<>\`{}` encoded again) and
* parsed again; `undefined` when the decode throws (the server answers 400).
*/
function readBack(id: string): string | undefined {
const base = '/_/'
const { pathname } = new URL(base + id, 'http://localhost')
let decoded = ''
try {
for (const part of pathname.split(/(%25|%5C)/i)) {
decoded += /^%(25|5C)$/i.test(part)
? part
: decodeURI(part).replace(
// eslint-disable-next-line no-control-regex
/[\x00-\x1f\x7f"<>`{}]/g,
(ch) =>
`%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`,
)
}
} catch {
return undefined
}
const read = new URL(decoded, 'http://localhost').pathname
return read.startsWith(base)
? read.slice(base.length).split('/')[0]
: undefined
}

/** The build error of a custom id `customIdCheck` refuses. */
export function customIdError(fn: CustomIdSubject, id: string): string {
return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. A server function id is one path segment of its URL: it cannot hold whitespace, control or non-ASCII characters or any of " # / < > ? \\ ^ \` { }, cannot be "." or "..", and cannot hold a percent-encoding the server reads as another id ("%41") or rejects. Use ASCII letters, digits, "-", ".", "_", "~" and "$".`
}

/** The build warning of a custom id `customIdCheck` deprecates. */
export function customIdWarning(fn: CustomIdSubject, id: string): string {
return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. Server function ids with characters other than ASCII letters, digits, "-", ".", "_", "~" and "$" are deprecated, and the next major version of TanStack Start rejects them: proxies and servers may encode or normalise them in the URL.`
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export function generateServerFnResolverModule(
? `,\n isClientReferenced: ${fn.isClientReferenced ?? true}`
: ''

return `'${id}': {
// (a custom id can hold `'`)
return `'${id.replace(/[\\']/g, '\\$&')}': {
functionName: '${fn.functionName}',
${moduleAccess}${clientReferenced}
}`
Expand Down
7 changes: 6 additions & 1 deletion packages/start-plugin-core/src/start-compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,19 @@ export interface ServerFn {
export type GenerateFunctionIdFn = (opts: {
filename: string
functionName: string
/** The server function's variable name, for diagnostics. */
variableName: string
extractedFilename: string
}) => string

/**
* Optional version that allows returning undefined to use default ID generation.
*/
export type GenerateFunctionIdFnOptional = (
opts: Omit<Parameters<GenerateFunctionIdFn>[0], 'extractedFilename'>,
opts: Omit<
Parameters<GenerateFunctionIdFn>[0],
'extractedFilename' | 'variableName'
>,
) => string | undefined

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,60 @@ describe('createServerFn compiles correctly', async () => {
expect(secondResult!.code).toContain('createSsrRpc("constant_id_1"')
})

// The client puts the id in the URL unencoded and the server reads that
// path segment back: a `/`, `#` or `?` cut it short (the call ran another
// server function of the file or none), a client percent-encodes `"`,
// `\`, whitespace, control and non-ASCII characters, URL parsing removes
// dot segments, and the server decodes a percent-encoding to another id or
// rejects it.
test.each([
'users/get',
'users#get',
'users?get',
'users"get',
'users\\get',
'users get',
'users\u0007get',
'utilisateurs-é',
'..',
'users%41get',
'x%c3%a9',
'%2E',
'users%zz',
])(
'a custom id the URL never carries whole fails the build: %j',
async (id) => {
const compiler = new StartCompiler({
env: 'client',
...getDefaultTestOptions('client'),
mode: 'build',
loadModule: async () => {},
lookupKinds: new Set(['ServerFn']),
lookupConfigurations: [
{
libName: '@tanstack/react-start',
rootExport: 'createServerFn',
kind: 'Root',
},
],
resolveId: async (id) => id,
generateFunctionId: () => id,
getKnownServerFns: () => ({}),
})
await expect(
compiler.compile({
code: `
import { createServerFn } from '@tanstack/react-start'
export const getUser = createServerFn().handler(async () => 'user')
`,
id: '/test/src/users.ts',
}),
).rejects.toThrow(
`[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function getUser (functionName "getUser_createServerFn_handler") of src/users.ts.`,
)
},
)

test('should resolve createServerFn from the same binding as a known root export', async () => {
const virtualModules: Record<string, string> = {
'@tanstack/start-client-core': `
Expand Down
11 changes: 9 additions & 2 deletions packages/start-plugin-core/tests/integration/start-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import os from 'node:os'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { createRsbuild } from '@rsbuild/core'
import { createBuilder, createServer } from 'vite'
import { createBuilder, createLogger, createServer } from 'vite'
import { onTestFinished } from 'vitest'
import type { ViteDevServer } from 'vite'

Expand Down Expand Up @@ -129,6 +129,8 @@ export interface StartBuild {
client: string
/** The server build's JavaScript. */
server: string
/** The warnings a Vite build logged (not collected for Rsbuild). */
warnings: Array<string>
}

/** Builds the app as `vite build` or `rsbuild build` does. */
Expand All @@ -138,11 +140,15 @@ export async function buildStartApp(
options: StartOptions = {},
): Promise<StartBuild> {
const plugin = await startPlugin(bundler, options)
const warnings: Array<string> = []
if (bundler === 'vite') {
const customLogger = createLogger('error')
customLogger.warn = (message) => warnings.push(message)
customLogger.warnOnce = customLogger.warn
const builder = await createBuilder({
root: app.root,
configFile: false,
logLevel: 'error',
customLogger,
plugins: [plugin],
})
await builder.buildApp()
Expand All @@ -157,6 +163,7 @@ export async function buildStartApp(
return {
client: await emittedCode(path.join(app.root, 'dist/client')),
server: await emittedCode(path.join(app.root, 'dist/server')),
warnings,
}
}

Expand Down
Loading
Loading