Open History to see the last commit
1import * as fs from 'node:fs'
2import { expect } from '@playwright/test'
3import { test } from '@tanstack/router-e2e-utils'
4import type { Page } from '@playwright/test'
5β
6const PORT = Number(process.env.E2E_APP_PORT ?? 0)
7β
8test('Server function URLs correctly include explicit ids', async ({
9 page,
10}) => {
11 const expectedIds: Record<string, string> = {
12 '/submit-post-formdata': 'submit-post-formdata-greetUser',
13 '/formdata-redirect': 'formdata-redirect-greetUser',
14 }
15β
16 for (const [currentPage, expectedId] of Object.entries(expectedIds)) {
17 await page.goto(currentPage)
18 await page.waitForLoadState('networkidle')
19β
20 const form = page.locator('form')
21 const actionUrl = await form.getAttribute('action')
22β
23 expect(actionUrl).toMatch(`/_serverFn/${expectedId}`)
24 }
25})
26β
27test('invoking a server function with custom response status code', async ({
28 page,
29}) => {
30 await page.goto('/status')
31β
32 await page.waitForLoadState('networkidle')
33β
34 const requestPromise = new Promise<void>((resolve) => {
35 page.on('response', (response) => {
36 expect(response.status()).toBe(225)
37 expect(response.statusText()).toBe('hello')
38 expect(response.headers()['content-type']).toContain('application/json')
39 resolve()
40 })
41 })
42 await page.getByTestId('invoke-server-fn').click()
43 await requestPromise
44})
45β
46test('Consistent server function returns both on client and server for GET and POST calls', async ({
47 page,
48}) => {
49 await page.goto('/consistent')
50β
51 await page.waitForLoadState('networkidle')
52 const expected =
53 (await page
54 .getByTestId('expected-consistent-server-fns-result')
55 .textContent()) || ''
56 expect(expected).not.toBe('')
57β
58 await expect(page.getByTestId('consistent-client-hydrated')).toBeAttached()
59β
60 await page.getByTestId('test-consistent-server-fn-calls-btn').click()
61 await page.waitForLoadState('networkidle')
62β
63 // GET calls
64 await expect(page.getByTestId('cons_serverGetFn1-response')).toContainText(
65 expected,
66 )
67 await expect(page.getByTestId('cons_getFn1-response')).toContainText(expected)
68β
69 // POST calls
70 await expect(page.getByTestId('cons_serverPostFn1-response')).toContainText(
71 expected,
72 )
73 await expect(page.getByTestId('cons_postFn1-response')).toContainText(
74 expected,
75 )
76})
77β
78test('submitting multipart/form-data as server function input', async ({
79 page,
80}) => {
81 await page.goto('/multipart')
82β
83 await page.waitForLoadState('networkidle')
84 const expected =
85 (await page
86 .getByTestId('expected-multipart-server-fn-result')
87 .textContent()) || ''
88 expect(expected).not.toBe('')
89β
90 const fileChooserPromise = page.waitForEvent('filechooser')
91 await page.getByTestId('multipart-form-file-input').click()
92 const fileChooser = await fileChooserPromise
93 await fileChooser.setFiles({
94 name: 'my_file.txt',
95 mimeType: 'text/plain',
96 buffer: Buffer.from('test data', 'utf-8'),
97 })
98 await page.getByText('Submit (onClick)').click()
99 await page.waitForLoadState('networkidle')
100β
101 await expect(page.getByTestId('multipart-form-response')).toContainText(
102 expected,
103 )
104})
105β
106test('isomorphic functions can have different implementations on client and server', async ({
107 page,
108}) => {
109 await page.goto('/isomorphic-fns')
110β
111 await page.waitForLoadState('networkidle')
112β
113 await page.getByTestId('test-isomorphic-results-btn').click()
114 await page.waitForLoadState('networkidle')
115β
116 await expect(page.getByTestId('server-result')).toContainText('server')
117 await expect(page.getByTestId('client-result')).toContainText('client')
118 await expect(page.getByTestId('ssr-result')).toContainText('server')
119β
120 await expect(page.getByTestId('server-echo-result')).toContainText(
121 'server received hello',
122 )
123 await expect(page.getByTestId('client-echo-result')).toContainText(
124 'client received hello',
125 )
126})
127β
128test('env-only functions can only be called on the server or client respectively', async ({
129 page,
130}) => {
131 await page.goto('/env-only')
132β
133 await page.waitForLoadState('networkidle')
134β
135 await page.getByTestId('test-env-only-results-btn').click()
136 await page.waitForLoadState('networkidle')
137β
138 await expect(page.getByTestId('server-on-server')).toContainText(
139 'server got: hello',
140 )
141 await expect(page.getByTestId('server-on-client')).toContainText(
142 'serverEcho threw an error: createServerOnlyFn() functions can only be called on the server!',
143 )
144β
145 await expect(page.getByTestId('client-on-server')).toContainText(
146 'clientEcho threw an error: createClientOnlyFn() functions can only be called on the client!',
147 )
148 await expect(page.getByTestId('client-on-client')).toContainText(
149 'client got: hello',
150 )
151})
152β
153test('Server function can return null for GET and POST calls', async ({
154 page,
155}) => {
156 await page.goto('/return-null')
157β
158 await page.waitForLoadState('networkidle')
159 await page.getByTestId('test-allow-server-fn-return-null-btn').click()
160 await page.waitForLoadState('networkidle')
161β
162 // GET call
163 await expect(
164 page.getByTestId('allow_return_null_getFn-response'),
165 ).toContainText(JSON.stringify(null))
166β
167 // POST call
168 await expect(
169 page.getByTestId('allow_return_null_postFn-response'),
170 ).toContainText(JSON.stringify(null))
171})
172β
173test('Server function can correctly send and receive FormData', async ({
174 page,
175}) => {
176 await page.goto('/serialize-form-data')
177β
178 await page.waitForLoadState('networkidle')
179 const expected =
180 (await page
181 .getByTestId('expected-serialize-formdata-server-fn-result')
182 .textContent()) || ''
183 expect(expected).not.toBe('')
184β
185 await page.getByTestId('test-serialize-formdata-fn-calls-btn').click()
186 await page.waitForLoadState('networkidle')
187β
188 await expect(
189 page.getByTestId('serialize-formdata-form-response'),
190 ).toContainText(expected)
191})
192β
193test('server function correctly passes context when using FormData', async ({
194 page,
195}) => {
196 await page.goto('/formdata-context')
197β
198 await page.waitForLoadState('networkidle')
199β
200 const expectedContextValue =
201 (await page.getByTestId('expected-formdata-context-value').textContent()) ||
202 ''
203 expect(expectedContextValue).toBe('context-from-middleware')
204β
205 // Test FormData function
206 await page.getByTestId('test-formdata-context-btn').click()
207 await page.waitForLoadState('networkidle')
208β
209 // Wait for the result to appear
210 await page.waitForSelector('[data-testid="formdata-context-result"]')
211β
212 const resultText =
213 (await page.getByTestId('formdata-context-result').textContent()) || ''
214 expect(resultText).not.toBe('')
215β
216 const result = JSON.parse(resultText)
217β
218 // Verify context was passed correctly for FormData function
219 expect(result.success).toBe(true)
220 expect(result.hasContext).toBe(true)
221 expect(result.name).toBe('TestUser')
222 expect(result.testString).toBeDefined()
223 expect(result.testString).toContain('context-from-middleware')
224β
225 // Test simple function (no parameters)
226 await page.getByTestId('test-simple-context-btn').click()
227 await page.waitForLoadState('networkidle')
228β
229 // Wait for the result to appear
230 await page.waitForSelector('[data-testid="formdata-context-result"]')
231β
232 const simpleResultText =
233 (await page.getByTestId('formdata-context-result').textContent()) || ''
234 expect(simpleResultText).not.toBe('')
235β
236 const simpleResult = JSON.parse(simpleResultText)
237β
238 // Verify context was passed correctly for simple function
239 expect(simpleResult.success).toBe(true)
240 expect(simpleResult.hasContext).toBe(true)
241 expect(simpleResult.testString).toBeDefined()
242 expect(simpleResult.testString).toContain('context-from-middleware')
243})
244β
245test('server function can correctly send and receive headers', async ({
246 page,
247}) => {
248 await page.goto('/headers')
249β
250 await page.waitForLoadState('networkidle')
251 let headers = JSON.parse(
252 await page.getByTestId('initial-headers-result').innerText(),
253 )
254 expect(headers['host']).toBe(`localhost:${PORT}`)
255 expect(headers['user-agent']).toContain('Mozilla/5.0')
256 expect(headers['sec-fetch-mode']).toBe('navigate')
257β
258 await page.getByTestId('test-headers-btn').click()
259 await page.waitForSelector('[data-testid="updated-headers-result"]')
260β
261 headers = JSON.parse(
262 await page.getByTestId('updated-headers-result').innerText(),
263 )
264β
265 expect(headers['host']).toBe(`localhost:${PORT}`)
266 expect(headers['user-agent']).toContain('Mozilla/5.0')
267 expect(headers['sec-fetch-mode']).toBe('cors')
268 expect(headers['referer']).toBe(`http://localhost:${PORT}/headers`)
269})
270β
271test('Direct POST submitting FormData to a Server function returns the correct message', async ({
272 page,
273}) => {
274 await page.goto('/submit-post-formdata')
275β
276 await page.waitForLoadState('networkidle')
277β
278 const expected =
279 (await page
280 .getByTestId('expected-submit-post-formdata-server-fn-result')
281 .textContent()) || ''
282 expect(expected).not.toBe('')
283β
284 await page.getByTestId('test-submit-post-formdata-fn-calls-btn').click()
285 await page.waitForLoadState('networkidle')
286β
287 const result = await page.innerText('body')
288 expect(result).toBe(expected)
289})
290β
291test('CSRF middleware rejects cross-site Server function requests', async ({
292 page,
293 request,
294}) => {
295 await page.goto('/submit-post-formdata')
296 await page.waitForLoadState('networkidle')
297β
298 const actionUrl = await page
299 .getByTestId('submit-post-formdata-form')
300 .getAttribute('action')
301β
302 expect(actionUrl).toBeTruthy()
303β
304 const response = await request.post(actionUrl!, {
305 headers: {
306 'Sec-Fetch-Site': 'cross-site',
307 },
308 multipart: {
309 name: 'Sean',
310 },
311 })
312β
313 expect(response.status()).toBe(403)
314 await expect(response.text()).resolves.toBe('Forbidden')
315})
316β
317test("server function's dead code is preserved if already there", async ({
318 page,
319}) => {
320 await page.goto('/dead-code-preserve')
321β
322 await page.waitForLoadState('networkidle')
323 await page.getByTestId('test-dead-code-fn-call-btn').click()
324 await page.waitForLoadState('networkidle')
325β
326 await expect(page.getByTestId('dead-code-fn-call-response')).toContainText(
327 '1',
328 )
329β
330 await fs.promises.rm('count-effect.txt')
331})
332β
333test.describe('server function sets cookies', () => {
334 async function runCookieTest(page: Page, expectedCookieValue: string) {
335 for (let i = 1; i <= 4; i++) {
336 const key = `cookie-${i}-${expectedCookieValue}`
337β
338 const actualValue = await page.getByTestId(key).textContent()
339 expect(actualValue).toBe(expectedCookieValue)
340 }
341 }
342 test('SSR', async ({ page }) => {
343 const expectedCookieValue = `SSR-${Date.now()}`
344 await page.goto(`/cookies/set?value=${expectedCookieValue}`)
345 await runCookieTest(page, expectedCookieValue)
346 })
347β
348 test('client side navigation', async ({ page }) => {
349 const expectedCookieValue = `CLIENT-${Date.now()}`
350 await page.goto(`/cookies?value=${expectedCookieValue}`)
351 await page.getByTestId('link-to-set').click()
352 await runCookieTest(page, expectedCookieValue)
353 })
354})
355;['GET', 'POST'].forEach((method) => {
356 test.describe(`aborting a server function call: method ${method}`, () => {
357 test('without aborting', async ({ page }) => {
358 await page.goto('/abort-signal/' + method)
359β
360 await page.waitForLoadState('networkidle')
361β
362 await page.getByTestId('run-without-abort-btn').click()
363 await page.waitForLoadState('networkidle')
364 await page.waitForSelector(
365 '[data-testid="result"]:has-text("server function result")',
366 )
367 await page.waitForSelector(
368 '[data-testid="errorMessage"]:has-text("$undefined")',
369 )
370β
371 const result = (await page.getByTestId('result').textContent()) || ''
372 expect(result).toBe('server function result')
373β
374 const errorMessage =
375 (await page.getByTestId('errorMessage').textContent()) || ''
376 expect(errorMessage).toBe('$undefined')
377 })
378β
379 test('aborting', async ({ page }) => {
380 await page.goto('/abort-signal/' + method)
381 await page.waitForLoadState('networkidle')
382β
383 await page.getByTestId('run-with-abort-btn').click()
384 await page.waitForLoadState('networkidle')
385 await page.waitForSelector(
386 '[data-testid="result"]:has-text("$undefined")',
387 )
388 await page.waitForSelector(
389 '[data-testid="errorMessage"]:has-text("aborted")',
390 )
391β
392 const result = (await page.getByTestId('result').textContent()) || ''
393 expect(result).toBe('$undefined')
394β
395 const errorMessage =
396 (await page.getByTestId('errorMessage').textContent()) || ''
397 expect(errorMessage).toContain('abort')
398 })
399 })
400})
401β
402test.describe('server functions with async validation', () => {
403 test.use({
404 whitelistErrors: [
405 'Failed to load resource: the server responded with a status of 500',
406 ],
407 })
408β
409 test('with valid input', async ({ page }) => {
410 await page.goto('/async-validation')
411β
412 await page.waitForLoadState('networkidle')
413β
414 await page.getByTestId('run-with-valid-btn').click()
415 await page.waitForLoadState('networkidle')
416 await page.waitForSelector('[data-testid="result"]:has-text("valid")')
417 await page.waitForSelector(
418 '[data-testid="errorMessage"]:has-text("$undefined")',
419 )
420β
421 const result = (await page.getByTestId('result').textContent()) || ''
422 expect(result).toBe('valid')
423β
424 const errorMessage =
425 (await page.getByTestId('errorMessage').textContent()) || ''
426 expect(errorMessage).toBe('$undefined')
427 })
428β
429 test('with invalid input', async ({ page }) => {
430 await page.goto('/async-validation')
431β
432 await page.waitForLoadState('networkidle')
433β
434 await page.getByTestId('run-with-invalid-btn').click()
435 await page.waitForLoadState('networkidle')
436 await page.waitForSelector('[data-testid="result"]:has-text("$undefined")')
437 await page.waitForSelector(
438 '[data-testid="errorMessage"]:has-text("invalid")',
439 )
440β
441 const result = (await page.getByTestId('result').textContent()) || ''
442 expect(result).toBe('$undefined')
443β
444 const errorMessage =
445 (await page.getByTestId('errorMessage').textContent()) || ''
446 expect(errorMessage).toContain('Invalid input')
447 })
448})
449β
450test('raw response', async ({ page }) => {
451 await page.goto('/raw-response')
452β
453 await page.waitForLoadState('networkidle')
454β
455 const expectedValue = (await page.getByTestId('expected').textContent()) || ''
456 expect(expectedValue).not.toBe('')
457β
458 await page.getByTestId('button').click()
459 await page.waitForLoadState('networkidle')
460β
461 await expect(page.getByTestId('response')).toContainText(expectedValue)
462})
463;[{ mode: 'js' }, { mode: 'no-js' }].forEach(({ mode }) => {
464 test(`Server function can redirect when sending formdata: mode = ${mode}`, async ({
465 page,
466 }) => {
467 await page.goto('/formdata-redirect?mode=' + mode)
468β
469 await page.waitForLoadState('networkidle')
470 const expected =
471 (await page
472 .getByTestId('expected-submit-post-formdata-server-fn-result')
473 .textContent()) || ''
474 expect(expected).not.toBe('')
475β
476 await page.getByTestId('test-submit-post-formdata-fn-calls-btn').click()
477β
478 await page.waitForLoadState('networkidle')
479β
480 await expect(
481 page.getByTestId('formdata-redirect-target-name'),
482 ).toContainText(expected)
483β
484 expect(page.url().endsWith(`/formdata-redirect/target/${expected}`))
485 })
486})
487β
488test.describe('middleware', () => {
489 test.describe('client middleware should have access to router context via the router instance', () => {
490 async function runTest(page: Page) {
491 await page.waitForLoadState('networkidle')
492β
493 const expected =
494 (await page.getByTestId('expected-server-fn-result').textContent()) ||
495 ''
496 expect(expected).not.toBe('')
497β
498 await page.getByTestId('btn-serverFn').click()
499 await page.waitForLoadState('networkidle')
500 await expect(page.getByTestId('serverFn-loader-result')).toContainText(
501 expected,
502 )
503 await expect(page.getByTestId('serverFn-client-result')).toContainText(
504 expected,
505 )
506 }
507β
508 test('direct visit', async ({ page }) => {
509 await page.goto('/middleware/client-middleware-router')
510 await runTest(page)
511 })
512β
513 test('client navigation', async ({ page }) => {
514 await page.goto('/middleware')
515 await page.getByTestId('client-middleware-router-link').click()
516 await runTest(page)
517 })
518 })
519β
520 test('server function in combination with request middleware', async ({
521 page,
522 }) => {
523 await page.goto('/middleware/request-middleware')
524β
525 await page.waitForLoadState('networkidle')
526β
527 async function checkEqual(prefix: string) {
528 const requestParam = await page
529 .getByTestId(`${prefix}-data-request-param`)
530 .textContent()
531 expect(requestParam).not.toBe('')
532 const requestFunc = await page
533 .getByTestId(`${prefix}-data-request-func`)
534 .textContent()
535 expect(requestParam).toBe(requestFunc)
536 }
537β
538 await checkEqual('loader')
539β
540 await page.getByTestId('client-call-button').click()
541 await page.waitForLoadState('networkidle')
542β
543 await checkEqual('client')
544 })
545})
546β
547test('factory', async ({ page }) => {
548 await page.goto('/factory')
549β
550 await expect(page.getByTestId('factory-route-component')).toBeInViewport()
551β
552 const buttons = await page
553 .locator('[data-testid^="btn-fn-"]')
554 .elementHandles()
555 for (const button of buttons) {
556 const testId = await button.getAttribute('data-testid')
557β
558 if (!testId) {
559 throw new Error('Button is missing data-testid')
560 }
561β
562 const suffix = testId.replace('btn-fn-', '')
563β
564 const expected =
565 (await page.getByTestId(`expected-fn-result-${suffix}`).textContent()) ||
566 ''
567 expect(expected).not.toBe('')
568β
569 await button.click()
570β
571 await expect(page.getByTestId(`fn-result-${suffix}`)).toContainText(
572 expected,
573 )
574β
575 await expect(page.getByTestId(`fn-comparison-${suffix}`)).toContainText(
576 'equal',
577 )
578 }
579})
580β
581test('primitives', async ({ page }) => {
582 await page.goto('/primitives')
583β
584 const testCases = await page
585 .locator('[data-testid^="expected-"]')
586 .elementHandles()
587 expect(testCases.length).not.toBe(0)
588β
589 for (const testCase of testCases) {
590 const testId = await testCase.getAttribute('data-testid')
591β
592 if (!testId) {
593 throw new Error('testcase is missing data-testid')
594 }
595β
596 const suffix = testId.replace('expected-', '')
597β
598 const expected =
599 (await page.getByTestId(`expected-${suffix}`).textContent()) || ''
600 expect(expected).not.toBe('')
601β
602 await expect(page.getByTestId(`result-${suffix}`)).toContainText(expected)
603 }
604})
605β
606test('redirect in server function on direct navigation', async ({ page }) => {
607 // Test direct navigation to a route with a server function that redirects
608 await page.goto('/redirect-test')
609β
610 // Should redirect to target page
611 await expect(page.getByTestId('redirect-target')).toBeVisible()
612 expect(page.url()).toContain('/redirect-test/target')
613})
614β
615test('redirect in server function called in query during SSR', async ({
616 page,
617}) => {
618 // Test direct navigation to a route with a server function that redirects
619 // when called inside a query with ssr: true
620 await page.goto('/redirect-test-ssr')
621β
622 // Should redirect to target page
623 await expect(page.getByTestId('redirect-target-ssr')).toBeVisible()
624 expect(page.url()).toContain('/redirect-test-ssr/target')
625})
626β
627test('re-exported server function factory middleware executes correctly', async ({
628 page,
629}) => {
630 // This test specifically verifies that when a server function factory is re-exported
631 // using `export { foo } from './module'` syntax, the middleware still executes.
632 // Previously, this syntax caused middleware to be silently skipped.
633 await page.goto('/factory')
634β
635 await expect(page.getByTestId('factory-route-component')).toBeInViewport()
636β
637 // Click the button for the re-exported factory function
638 await page.getByTestId('btn-fn-reexportedFactoryFn').click()
639β
640 // Wait for the result
641 await expect(page.getByTestId('fn-result-reexportedFactoryFn')).toContainText(
642 'reexport-middleware-executed',
643 )
644β
645 // Verify the full context was returned (middleware executed)
646 await expect(
647 page.getByTestId('fn-comparison-reexportedFactoryFn'),
648 ).toContainText('equal')
649})
650β
651test('star re-exported server function factory middleware executes correctly', async ({
652 page,
653}) => {
654 // This test specifically verifies that when a server function factory is re-exported
655 // using `export * from './module'` syntax, the middleware still executes.
656 // Previously, this syntax caused middleware to be silently skipped.
657 await page.goto('/factory')
658β
659 await expect(page.getByTestId('factory-route-component')).toBeInViewport()
660β
661 // Click the button for the star re-exported factory function
662 await page.getByTestId('btn-fn-starReexportedFactoryFn').click()
663β
664 // Wait for the result
665 await expect(
666 page.getByTestId('fn-result-starReexportedFactoryFn'),
667 ).toContainText('star-reexport-middleware-executed')
668β
669 // Verify the full context was returned (middleware executed)
670 await expect(
671 page.getByTestId('fn-comparison-starReexportedFactoryFn'),
672 ).toContainText('equal')
673})
674β
675test('nested star re-exported server function factory middleware executes correctly', async ({
676 page,
677}) => {
678 // This test specifically verifies that when a server function factory is re-exported
679 // through a nested chain (A -> B -> C) using `export * from './module'` syntax,
680 // the middleware still executes correctly.
681 await page.goto('/factory')
682β
683 await expect(page.getByTestId('factory-route-component')).toBeInViewport()
684β
685 // Click the button for the nested re-exported factory function
686 await page.getByTestId('btn-fn-nestedReexportedFactoryFn').click()
687β
688 // Wait for the result
689 await expect(
690 page.getByTestId('fn-result-nestedReexportedFactoryFn'),
691 ).toContainText('nested-middleware-executed')
692β
693 // Verify the full context was returned (middleware executed)
694 await expect(
695 page.getByTestId('fn-comparison-nestedReexportedFactoryFn'),
696 ).toContainText('equal')
697})
698β
699test('server-only imports in middleware.server() are stripped from client build', async ({
700 page,
701}) => {
702 // This test verifies that server-only imports (like getRequestHeaders from @tanstack/react-start/server)
703 // inside createMiddleware().server() are properly stripped from the client build.
704 // If the .server() part is not removed, the build would fail with node:async_hooks externalization errors.
705 // The fact that this page loads at all proves the server code was stripped correctly.
706 await page.goto('/middleware/server-import-middleware')
707β
708 await page.waitForLoadState('networkidle')
709β
710 // Click the button to call the server function with middleware
711 await page.getByTestId('test-server-import-middleware-btn').click()
712β
713 // Wait for the result - should contain our custom test header value
714 await expect(
715 page.getByTestId('server-import-middleware-result'),
716 ).toContainText('test-header-value')
717})
718β
719test('middleware factories with server-only imports are stripped from client build', async ({
720 page,
721}) => {
722 // This test verifies that middleware factories (functions returning createMiddleware().server())
723 // with server-only imports are properly stripped from the client build.
724 // If the .server() part inside the factory is not removed, the build would fail with
725 // node:async_hooks externalization errors because getRequestHeaders uses node:async_hooks internally.
726 // The fact that this page loads at all proves the server code was stripped correctly.
727 await page.goto('/middleware/middleware-factory')
728β
729 await page.waitForLoadState('networkidle')
730β
731 // Click the button to call the server function with factory middlewares
732 await page.getByTestId('test-middleware-factory-btn').click()
733β
734 // Wait for the result - should contain our custom header value from the factory middleware
735 await expect(page.getByTestId('header-value')).toContainText(
736 'factory-header-value',
737 )
738β
739 // Also verify the prefixed headers were matched correctly
740 await expect(page.getByTestId('matched-headers')).toContainText(
741 'x-factory-one',
742 )
743 await expect(page.getByTestId('matched-headers')).toContainText(
744 'x-factory-two',
745 )
746})
747β
748test('redirect via server function with middleware does not cause serialization error (issue #5372)', async ({
749 page,
750}) => {
751 // This test verifies that throwing a redirect from a server function
752 // that has middleware attached does not cause a SerovalUnsupportedTypeError.
753 // Issue #5372: Middleware causes serialization error when throwing redirects via server function
754 await page.goto('/middleware/redirect-with-middleware')
755β
756 await page.waitForLoadState('networkidle')
757β
758 // Verify we're on the source page
759 await expect(page.getByTestId('middleware-redirect-source')).toBeVisible()
760β
761 // Click the button to trigger the redirect via server function with middleware
762 await page.getByTestId('trigger-redirect-btn').click()
763β
764 // Should redirect to target page without serialization error
765 await expect(page.getByTestId('middleware-redirect-target')).toBeVisible()
766 expect(page.url()).toContain('/middleware/redirect-with-middleware/target')
767β
768 // Verify no error was shown (would indicate serialization failure)
769 await expect(page.getByTestId('error-message')).not.toBeVisible()
770})
771β
772test.describe('unhandled exception in middleware (issue #5266)', () => {
773 // Whitelist expected browser console errors since this test verifies error handling.
774 test.use({ whitelistErrors: ['500', 'Unhandled middleware exception'] })
775β
776 test('does not crash server and shows error component', async ({ page }) => {
777 // This test verifies that when a middleware throws an unhandled exception,
778 // the server does not crash and the error is properly caught and displayed.
779 // Issue #5266: Server crashes when unhandled exception in server function or middleware
780 await page.goto('/middleware/unhandled-exception')
781β
782 // The error should be caught and displayed via errorComponent
783 await expect(page.getByTestId('unhandled-exception-error')).toBeVisible()
784β
785 // Verify the error message is shown
786 await expect(page.getByTestId('error-message')).toBeVisible()
787β
788 // The route component should NOT render since error was thrown
789 await expect(page.getByTestId('route-success')).not.toBeVisible()
790 })
791})
792β
793test('function middleware receives serverFnMeta in options', async ({
794 page,
795}) => {
796 // This test verifies that:
797 // 1. Client middleware receives serverFnMeta with just { id } - NOT name or filename
798 // 2. Server middleware receives serverFnMeta with full { id, name, filename }
799 // 3. Request middleware receives serverFnMeta with full { id, name, filename } for server function calls
800 // 4. Request middleware receives serverFnMeta as undefined for page requests (not server function calls)
801 // 5. Client middleware can send the function metadata to the server via sendContext
802 await page.goto('/middleware/function-metadata')
803β
804 await page.waitForLoadState('networkidle')
805β
806 // First, verify that for page requests, serverFnMeta is undefined
807 // This is captured by the route-level server middleware and passed via serverContext
808 // The middleware sets '$undefined' string to prove we actually executed and passed data through
809 const pageRequestServerFnMeta = await page
810 .getByTestId('page-request-server-fn-meta')
811 .textContent()
812 expect(pageRequestServerFnMeta).toBe('$undefined')
813β
814 // Verify SSR data - server captured metadata should have full properties
815 const loaderFunctionId = await page
816 .getByTestId('loader-function-id')
817 .textContent()
818 const loaderFunctionName = await page
819 .getByTestId('loader-function-name')
820 .textContent()
821 const loaderFilename = await page.getByTestId('loader-filename').textContent()
822 const loaderClientCapturedId = await page
823 .getByTestId('loader-client-captured-id')
824 .textContent()
825 const loaderClientCapturedName = await page
826 .getByTestId('loader-client-captured-name')
827 .textContent()
828 const loaderClientCapturedFilename = await page
829 .getByTestId('loader-client-captured-filename')
830 .textContent()
831 const loaderRequestCapturedId = await page
832 .getByTestId('loader-request-captured-id')
833 .textContent()
834 const loaderRequestCapturedName = await page
835 .getByTestId('loader-request-captured-name')
836 .textContent()
837 const loaderRequestCapturedFilename = await page
838 .getByTestId('loader-request-captured-filename')
839 .textContent()
840β
841 // id should be a non-empty string
842 expect(loaderFunctionId).toBeTruthy()
843 expect(loaderFunctionId!.length).toBeGreaterThan(0)
844β
845 // name should be the variable name of the server function
846 expect(loaderFunctionName).toBeTruthy()
847 expect(loaderFunctionName).toBe('getMetadataFn')
848β
849 // filename should be the exact route file path
850 expect(loaderFilename).toBe('src/routes/middleware/function-metadata.tsx')
851β
852 // Client captured ID should match the server function id
853 // (sent via client middleware's sendContext)
854 expect(loaderClientCapturedId).toBe(loaderFunctionId)
855β
856 // Client middleware should NOT have access to name or filename
857 // These should be "undefined" (the fallback value we display in the UI)
858 expect(loaderClientCapturedName).toBe('undefined')
859 expect(loaderClientCapturedFilename).toBe('undefined')
860β
861 // Request middleware should have full metadata (id, name, filename)
862 // since it runs server-side during server function calls
863 expect(loaderRequestCapturedId).toBe(loaderFunctionId)
864 expect(loaderRequestCapturedName).toBe('getMetadataFn')
865 expect(loaderRequestCapturedFilename).toBe(
866 'src/routes/middleware/function-metadata.tsx',
867 )
868β
869 // Now test client-side call
870 await page.getByTestId('call-server-fn-btn').click()
871 await page.waitForSelector('[data-testid="client-data"]')
872β
873 const clientFunctionId = await page
874 .getByTestId('client-function-id')
875 .textContent()
876 const clientFunctionName = await page
877 .getByTestId('client-function-name')
878 .textContent()
879 const clientFilename = await page.getByTestId('client-filename').textContent()
880 const clientClientCapturedId = await page
881 .getByTestId('client-client-captured-id')
882 .textContent()
883 const clientClientCapturedName = await page
884 .getByTestId('client-client-captured-name')
885 .textContent()
886 const clientClientCapturedFilename = await page
887 .getByTestId('client-client-captured-filename')
888 .textContent()
889 const clientRequestCapturedId = await page
890 .getByTestId('client-request-captured-id')
891 .textContent()
892 const clientRequestCapturedName = await page
893 .getByTestId('client-request-captured-name')
894 .textContent()
895 const clientRequestCapturedFilename = await page
896 .getByTestId('client-request-captured-filename')
897 .textContent()
898β
899 // Client call should get the same server metadata
900 expect(clientFunctionId).toBe(loaderFunctionId)
901 expect(clientFunctionName).toBe(loaderFunctionName)
902 expect(clientFilename).toBe(loaderFilename)
903β
904 // Client captured ID from client middleware should also match
905 expect(clientClientCapturedId).toBe(loaderFunctionId)
906β
907 // Client middleware should NOT have access to name or filename
908 expect(clientClientCapturedName).toBe('undefined')
909 expect(clientClientCapturedFilename).toBe('undefined')
910β
911 // Request middleware should have full metadata for client-side calls too
912 expect(clientRequestCapturedId).toBe(loaderFunctionId)
913 expect(clientRequestCapturedName).toBe('getMetadataFn')
914 expect(clientRequestCapturedFilename).toBe(
915 'src/routes/middleware/function-metadata.tsx',
916 )
917})
918β
919test('server function is called with correct method option', async ({
920 page,
921}) => {
922 await page.goto('/function-method', { waitUntil: 'networkidle' })
923β
924 await expect(page.getByTestId('method-route-component')).toBeInViewport()
925β
926 const buttons = await page
927 .locator('[data-testid^="btn-fn-"]')
928 .elementHandles()
929 for (const button of buttons) {
930 const testId = await button.getAttribute('data-testid')
931β
932 if (!testId) {
933 throw new Error('Button is missing data-testid')
934 }
935β
936 const suffix = testId.replace('btn-fn-', '')
937β
938 const expected =
939 (await page.getByTestId(`expected-fn-result-${suffix}`).textContent()) ||
940 ''
941 expect(expected).not.toBe('')
942β
943 await button.click()
944β
945 await expect(page.getByTestId(`fn-result-${suffix}`)).toContainText(
946 expected,
947 )
948β
949 await expect(page.getByTestId(`fn-comparison-${suffix}`)).toContainText(
950 'equal',
951 )
952 }
953})
954β
955test('server function receives serverFnMeta in options', async ({ page }) => {
956 // This test verifies that:
957 // 1. Server functions receive `serverFnMeta` with full { id, name, filename }
958 // 2. No1 works even when the said server function is called from another server function
959β
960 await page.goto('/function-metadata', { waitUntil: 'networkidle' })
961β
962 await expect(page.getByTestId('metadata-route-component')).toBeInViewport()
963β
964 // Test for no1
965 const loaderNormalGet = await page
966 .getByTestId('loader-normal-get-function-metadata')
967 .textContent()
968 const loaderNormalPost = await page
969 .getByTestId('loader-normal-post-function-metadata')
970 .textContent()
971β
972 // stringified metadata should not be empty string
973 expect(loaderNormalGet).toBeTruthy()
974 // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string
975 const normalGetMetadata = JSON.parse(loaderNormalGet!)
976 expect(normalGetMetadata).toHaveProperty('id')
977 expect(normalGetMetadata).toHaveProperty('name')
978 expect(normalGetMetadata).toHaveProperty('filename')
979 expect(typeof normalGetMetadata.id).toBe('string')
980 expect(normalGetMetadata.id.length).toBeGreaterThan(0)
981 expect(typeof normalGetMetadata.name).toBe('string')
982 expect(normalGetMetadata.name.length).toBeGreaterThan(0)
983 expect(typeof normalGetMetadata.filename).toBe('string')
984 expect(normalGetMetadata.filename.length).toBeGreaterThan(0)
985β
986 // stringified metadata should not be empty string
987 expect(loaderNormalPost).toBeTruthy()
988 // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string
989 const normalPostMetadata = JSON.parse(loaderNormalPost!)
990 expect(normalPostMetadata).toHaveProperty('id')
991 expect(normalPostMetadata).toHaveProperty('name')
992 expect(normalPostMetadata).toHaveProperty('filename')
993 expect(typeof normalPostMetadata.id).toBe('string')
994 expect(normalPostMetadata.id.length).toBeGreaterThan(0)
995 expect(typeof normalPostMetadata.name).toBe('string')
996 expect(normalPostMetadata.name.length).toBeGreaterThan(0)
997 expect(typeof normalPostMetadata.filename).toBe('string')
998 expect(normalPostMetadata.filename.length).toBeGreaterThan(0)
999β
1000 // Test for no2
1001 const loaderNestingGet = await page
1002 .getByTestId('loader-nesting-get-function-metadata')
1003 .textContent()
1004 const loaderNestingPost = await page
1005 .getByTestId('loader-nesting-post-function-metadata')
1006 .textContent()
1007β
1008 // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string
1009 const nestingGetMetadata = JSON.parse(loaderNestingGet!)
1010 expect(nestingGetMetadata).toHaveProperty('meta.id')
1011 expect(nestingGetMetadata).toHaveProperty('meta.name')
1012 expect(nestingGetMetadata).toHaveProperty('meta.filename')
1013 expect(typeof nestingGetMetadata.meta.id).toBe('string')
1014 expect(nestingGetMetadata.meta.id.length).toBeGreaterThan(0)
1015 expect(typeof nestingGetMetadata.meta.name).toBe('string')
1016 expect(nestingGetMetadata.meta.name.length).toBeGreaterThan(0)
1017 expect(typeof nestingGetMetadata.meta.filename).toBe('string')
1018 expect(nestingGetMetadata.meta.filename.length).toBeGreaterThan(0)
1019 expect(nestingGetMetadata).toHaveProperty('inner.get.id')
1020 expect(nestingGetMetadata).toHaveProperty('inner.get.name')
1021 expect(nestingGetMetadata).toHaveProperty('inner.get.filename')
1022 expect(nestingGetMetadata.inner.get.id.length).toBeGreaterThan(0)
1023 expect(nestingGetMetadata.inner.get.name.length).toBeGreaterThan(0)
1024 expect(nestingGetMetadata.inner.get.filename.length).toBeGreaterThan(0)
1025 expect(nestingGetMetadata).toHaveProperty('inner.post.id')
1026 expect(nestingGetMetadata).toHaveProperty('inner.post.name')
1027 expect(nestingGetMetadata).toHaveProperty('inner.post.filename')
1028 expect(nestingGetMetadata.inner.post.id.length).toBeGreaterThan(0)
1029 expect(nestingGetMetadata.inner.post.name.length).toBeGreaterThan(0)
1030 expect(nestingGetMetadata.inner.post.filename.length).toBeGreaterThan(0)
1031β
1032 // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string
1033 const nestingPostMetadata = JSON.parse(loaderNestingPost!)
1034 expect(nestingPostMetadata).toHaveProperty('meta.id')
1035 expect(nestingPostMetadata).toHaveProperty('meta.name')
1036 expect(nestingPostMetadata).toHaveProperty('meta.filename')
1037 expect(typeof nestingPostMetadata.meta.id).toBe('string')
1038 expect(nestingPostMetadata.meta.id.length).toBeGreaterThan(0)
1039 expect(typeof nestingPostMetadata.meta.name).toBe('string')
1040 expect(nestingPostMetadata.meta.name.length).toBeGreaterThan(0)
1041 expect(typeof nestingPostMetadata.meta.filename).toBe('string')
1042 expect(nestingPostMetadata.meta.filename.length).toBeGreaterThan(0)
1043 expect(nestingPostMetadata).toHaveProperty('inner.get.id')
1044 expect(nestingPostMetadata).toHaveProperty('inner.get.name')
1045 expect(nestingPostMetadata).toHaveProperty('inner.get.filename')
1046 expect(nestingPostMetadata.inner.get.id.length).toBeGreaterThan(0)
1047 expect(nestingPostMetadata.inner.get.name.length).toBeGreaterThan(0)
1048 expect(nestingPostMetadata.inner.get.filename.length).toBeGreaterThan(0)
1049 expect(nestingPostMetadata).toHaveProperty('inner.post.id')
1050 expect(nestingPostMetadata).toHaveProperty('inner.post.name')
1051 expect(nestingPostMetadata).toHaveProperty('inner.post.filename')
1052 expect(nestingPostMetadata.inner.post.id.length).toBeGreaterThan(0)
1053 expect(nestingPostMetadata.inner.post.name.length).toBeGreaterThan(0)
1054 expect(nestingPostMetadata.inner.post.filename.length).toBeGreaterThan(0)
1055})
1056β
1057test('middleware can catch errors thrown by server function handlers', async ({
1058 page,
1059}) => {
1060 await page.goto('/middleware/catch-handler-error')
1061β
1062 await page.waitForLoadState('networkidle')
1063β
1064 await expect(page.getByTestId('catch-handler-error-title')).toBeVisible()
1065β
1066 await page.getByTestId('trigger-error-btn').click()
1067β
1068 await expect(page.getByTestId('transformed-error')).toBeVisible()
1069β
1070 await expect(page.getByTestId('transformed-error')).toContainText(
1071 'Middleware caught and transformed',
1072 )
1073β
1074 await expect(page.getByTestId('transformed-error')).toContainText(
1075 'This error should be caught by middleware',
1076 )
1077})
1078β
1079test('server function with custom fetch implementation passed directly', async ({
1080 page,
1081}) => {
1082 await page.goto('/custom-fetch')
1083 await page.waitForLoadState('networkidle')
1084β
1085 await page.getByTestId('test-direct-custom-fetch-btn').click()
1086 await page.waitForSelector(
1087 '[data-testid="direct-custom-fetch-result"]:not(:has-text("null"))',
1088 )
1089β
1090 const result = await page
1091 .getByTestId('direct-custom-fetch-result')
1092 .textContent()
1093 expect(result).toContain('x-custom-fetch-direct')
1094})
1095β
1096test('server function with custom fetch implementation via middleware', async ({
1097 page,
1098}) => {
1099 await page.goto('/custom-fetch')
1100 await page.waitForLoadState('networkidle')
1101β
1102 await page.getByTestId('test-middleware-custom-fetch-btn').click()
1103 await page.waitForSelector(
1104 '[data-testid="middleware-custom-fetch-result"]:not(:has-text("null"))',
1105 )
1106β
1107 const result = await page
1108 .getByTestId('middleware-custom-fetch-result')
1109 .textContent()
1110 expect(result).toContain('x-custom-fetch-middleware')
1111})
1112β
1113test('server function with chained middleware - later middleware overrides earlier', async ({
1114 page,
1115}) => {
1116 await page.goto('/custom-fetch')
1117 await page.waitForLoadState('networkidle')
1118β
1119 await page.getByTestId('test-chained-middleware-btn').click()
1120 await page.waitForSelector(
1121 '[data-testid="chained-middleware-result"]:not(:has-text("null"))',
1122 )
1123β
1124 const result = await page
1125 .getByTestId('chained-middleware-result')
1126 .textContent()
1127 // Second middleware should override first, so only x-middleware-second should be present
1128 expect(result).toContain('x-middleware-second')
1129 expect(result).not.toContain('x-middleware-first')
1130})
1131β
1132test('server function with direct fetch overrides middleware fetch', async ({
1133 page,
1134}) => {
1135 await page.goto('/custom-fetch')
1136 await page.waitForLoadState('networkidle')
1137β
1138 await page.getByTestId('test-direct-override-btn').click()
1139 await page.waitForSelector(
1140 '[data-testid="direct-override-result"]:not(:has-text("null"))',
1141 )
1142β
1143 const result = await page.getByTestId('direct-override-result').textContent()
1144 // Direct fetch should override middleware, so x-direct-override should be present
1145 // and x-custom-fetch-middleware should NOT be present
1146 expect(result).toContain('x-direct-override')
1147 expect(result).not.toContain('x-custom-fetch-middleware')
1148})
1149β
1150test('server function without custom fetch uses global serverFnFetch from createStart', async ({
1151 page,
1152}) => {
1153 await page.goto('/custom-fetch')
1154 await page.waitForLoadState('networkidle')
1155β
1156 await page.getByTestId('test-no-custom-fetch-btn').click()
1157 await page.waitForLoadState('networkidle')
1158 await page.waitForSelector(
1159 '[data-testid="no-custom-fetch-result"]:not(:has-text("null"))',
1160 )
1161β
1162 const result = await page.getByTestId('no-custom-fetch-result').textContent()
1163 // Global serverFnFetch header should be present
1164 expect(result).toContain('x-global-fetch')
1165 // No other custom headers should be present
1166 expect(result).not.toContain('x-custom-fetch-direct')
1167 expect(result).not.toContain('x-custom-fetch-middleware')
1168 expect(result).not.toContain('x-middleware-first')
1169 expect(result).not.toContain('x-middleware-second')
1170 expect(result).not.toContain('x-direct-override')
1171})
1172β
1173test('server function uses global serverFnFetch from createStart', async ({
1174 page,
1175}) => {
1176 await page.goto('/custom-fetch')
1177 await page.waitForLoadState('networkidle')
1178β
1179 await page.getByTestId('test-global-fetch-btn').click()
1180 await page.waitForSelector(
1181 '[data-testid="global-fetch-result"]:not(:has-text("null"))',
1182 )
1183β
1184 const result = await page.getByTestId('global-fetch-result').textContent()
1185 // Global serverFnFetch header should be present
1186 expect(result).toContain('x-global-fetch')
1187})
1188β
1189test('middleware fetch overrides global serverFnFetch from createStart', async ({
1190 page,
1191}) => {
1192 await page.goto('/custom-fetch')
1193 await page.waitForLoadState('networkidle')
1194β
1195 await page.getByTestId('test-middleware-overrides-global-btn').click()
1196 await page.waitForSelector(
1197 '[data-testid="middleware-overrides-global-result"]:not(:has-text("null"))',
1198 )
1199β
1200 const result = await page
1201 .getByTestId('middleware-overrides-global-result')
1202 .textContent()
1203 // Middleware fetch should override global, so x-custom-fetch-middleware should be present
1204 expect(result).toContain('x-custom-fetch-middleware')
1205 // Global fetch header should NOT be present (overridden by middleware)
1206 expect(result).not.toContain('x-global-fetch')
1207})
1208β
1209test('direct fetch overrides global serverFnFetch from createStart', async ({
1210 page,
1211}) => {
1212 await page.goto('/custom-fetch')
1213 await page.waitForLoadState('networkidle')
1214β
1215 await page.getByTestId('test-direct-overrides-global-btn').click()
1216 await page.waitForSelector(
1217 '[data-testid="direct-overrides-global-result"]:not(:has-text("null"))',
1218 )
1219β
1220 const result = await page
1221 .getByTestId('direct-overrides-global-result')
1222 .textContent()
1223 // Direct fetch should override global, so x-direct-override-global should be present
1224 expect(result).toContain('x-direct-override-global')
1225 // Global fetch header should NOT be present (overridden by direct fetch)
1226 expect(result).not.toContain('x-global-fetch')
1227})
1228β
1229test.describe('server function returns 405 when method is not allowed', () => {
1230 // Whitelist the expected 405 error since this test verifies method mismatch handling
1231 test.use({ whitelistErrors: ['405'] })
1232β
1233 async function runMethodNotAllowedTest(
1234 page: Page,
1235 methodParam: string,
1236 allowedMethod: string,
1237 ) {
1238 await page.goto(`/method-not-allowed/${methodParam}`)
1239 await page.waitForLoadState('networkidle')
1240β
1241 for (const testMethod of ['GET', 'POST', 'PUT', 'OPTIONS']) {
1242 const lower = testMethod.toLowerCase()
1243 await page.getByTestId(`${lower}-button`).click()
1244 await page.waitForLoadState('networkidle')
1245β
1246 if (testMethod === allowedMethod) {
1247 await expect(page.getByTestId(`${lower}-fetch-result`)).toContainText(
1248 '[200,"Hello, World!"]',
1249 )
1250 } else {
1251 await expect(page.getByTestId(`${lower}-fetch-result`)).toContainText(
1252 `[405,"expected ${allowedMethod} method. Got ${testMethod}"]`,
1253 )
1254 }
1255 }
1256 }
1257β
1258 test('serverFn defined with GET method', async ({ page }) => {
1259 await runMethodNotAllowedTest(page, 'get', 'GET')
1260 })
1261β
1262 test('serverFn without explicit method', async ({ page }) => {
1263 await runMethodNotAllowedTest(page, 'undefined', 'GET')
1264 })
1265β
1266 test('serverFn defined with POST method', async ({ page }) => {
1267 await runMethodNotAllowedTest(page, 'post', 'POST')
1268 })
1269})