Open History to see the last commit
1import { afterEach, describe, expect, test, vi } from 'vitest'
2import {
3 act,
4 cleanup,
5 fireEvent,
6 render,
7 screen,
8 waitFor,
9} from '@testing-library/react'
10import { createPortal } from 'react-dom'
11import ReactDOMServer from 'react-dom/server'
12import { hydrate } from '@tanstack/router-core/ssr/client'
13import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id'
14β
15import {
16 HeadContent,
17 Link,
18 Outlet,
19 RouterContextProvider,
20 RouterProvider,
21 createBrowserHistory,
22 createMemoryHistory,
23 createRootRoute,
24 createRoute,
25 createRouter,
26} from '../src'
27import { Scripts } from '../src/Scripts'
28import type { Manifest } from '@tanstack/router-core'
29β
30// React 19 keeps stylesheet resources keyed by href alive for the lifetime of
31// the test module, so these tests use explicit asset URLs to avoid collisions
32// between cases even though Testing Library cleanup runs after each test.
33const createTestManifest = (
34 routeId: string,
35 options?: {
36 stylesheetHref?: string
37 preloadHref?: string
38 scriptFormat?: Manifest['scriptFormat']
39 },
40) =>
41 ({
42 ...(options?.scriptFormat ? { scriptFormat: options.scriptFormat } : {}),
43 routes: {
44 [routeId]: {
45 preloads: [options?.preloadHref ?? '/main.js'],
46 css: [options?.stylesheetHref ?? '/main.css'],
47 },
48 },
49 }) satisfies Manifest
50β
51const browserHistories: Array<ReturnType<typeof createBrowserHistory>> = []
52β
53const createTestBrowserHistory = () => {
54 const history = createBrowserHistory()
55 browserHistories.push(history)
56 return history
57}
58β
59afterEach(() => {
60 cleanup()
61 browserHistories.splice(0).forEach((history) => history.destroy())
62 window.history.replaceState(null, 'root', '/')
63 delete window.$_TSR
64})
65β
66describe('ssr scripts', () => {
67 test('it works', async () => {
68 const rootRoute = createRootRoute({
69 head: () => {
70 return {
71 scripts: [
72 {
73 src: 'script.js',
74 },
75 {
76 src: 'script2.js',
77 },
78 ],
79 }
80 },
81 component: () => {
82 return (
83 <div>
84 <div data-testid="root">root</div>
85 <Outlet />
86 <Scripts />
87 </div>
88 )
89 },
90 })
91β
92 const indexRoute = createRoute({
93 path: '/',
94 getParentRoute: () => rootRoute,
95 head: () => {
96 return {
97 scripts: [
98 {
99 src: 'script3.js',
100 },
101 ],
102 }
103 },
104 })
105β
106 const router = createRouter({
107 history: createMemoryHistory({
108 initialEntries: ['/'],
109 }),
110 routeTree: rootRoute.addChildren([indexRoute]),
111 isServer: true,
112 })
113β
114 await router.load()
115β
116 expect(router.state.matches.map((d) => d.headScripts).flat(1)).toEqual([
117 { src: 'script.js' },
118 { src: 'script2.js' },
119 { src: 'script3.js' },
120 ])
121 })
122β
123 test('excludes `undefined` script values', async () => {
124 const rootRoute = createRootRoute({
125 scripts: () => [
126 { src: 'script.js' },
127 undefined, // 'script2.js' opted out by certain conditions, such as `NODE_ENV=production`.
128 ],
129 component: () => {
130 return (
131 <div>
132 <div data-testid="root">root</div>
133 <Outlet />
134 <Scripts />
135 </div>
136 )
137 },
138 })
139β
140 const indexRoute = createRoute({
141 path: '/',
142 getParentRoute: () => rootRoute,
143 scripts: () => [{ src: 'script3.js' }],
144 component: () => {
145 return <div data-testid="index">index</div>
146 },
147 })
148β
149 const router = createRouter({
150 history: createMemoryHistory({
151 initialEntries: ['/'],
152 }),
153 routeTree: rootRoute.addChildren([indexRoute]),
154 isServer: true,
155 })
156β
157 await router.load()
158β
159 expect(router.state.matches.map((d) => d.scripts).flat(1)).toEqual([
160 { src: 'script.js' },
161 undefined,
162 { src: 'script3.js' },
163 ])
164β
165 const html = ReactDOMServer.renderToString(
166 <RouterProvider router={router} />,
167 )
168 expect(html).toContain('<script src="script.js"></script>')
169 expect(html).toContain('<script src="script3.js"></script>')
170 expect(html).not.toContain('script2.js')
171 })
172})
173β
174describe('scripts with async/defer attributes', () => {
175 test('server renders scripts with async/defer attributes in output', async () => {
176 const rootRoute = createRootRoute({
177 scripts: () => [
178 {
179 src: 'script.js',
180 async: true,
181 },
182 {
183 src: 'script2.js',
184 defer: true,
185 },
186 ],
187 component: () => {
188 return (
189 <div>
190 <div data-testid="server-root">root</div>
191 <Outlet />
192 <Scripts />
193 </div>
194 )
195 },
196 })
197β
198 const indexRoute = createRoute({
199 path: '/',
200 getParentRoute: () => rootRoute,
201 component: () => {
202 return <div data-testid="server-index">index</div>
203 },
204 })
205β
206 const router = createRouter({
207 history: createMemoryHistory({
208 initialEntries: ['/'],
209 }),
210 routeTree: rootRoute.addChildren([indexRoute]),
211 isServer: true,
212 })
213β
214 await router.load()
215β
216 // Use ReactDOMServer.renderToString to test actual server output
217 const html = ReactDOMServer.renderToString(
218 <RouterProvider router={router} />,
219 )
220β
221 expect(html).toMatch(/<script[^>]*src="script\.js"[^>]*async=""/)
222 expect(html).toMatch(/<script[^>]*src="script2\.js"[^>]*defer=""/)
223 })
224β
225 test('server keeps manifest src scripts in document order', async () => {
226 const clientEntryAsset = {
227 attrs: {
228 src: '/entry.js',
229 type: 'module',
230 async: true,
231 },
232 } satisfies NonNullable<Manifest['routes'][string]['scripts']>[number]
233β
234 const rootRoute = createRootRoute({
235 component: () => {
236 return (
237 <html>
238 <head />
239 <body>
240 <main data-testid="content">content</main>
241 <Outlet />
242 <Scripts />
243 </body>
244 </html>
245 )
246 },
247 })
248β
249 const indexRoute = createRoute({
250 path: '/',
251 getParentRoute: () => rootRoute,
252 })
253β
254 const router = createRouter({
255 history: createMemoryHistory({
256 initialEntries: ['/'],
257 }),
258 routeTree: rootRoute.addChildren([indexRoute]),
259 isServer: true,
260 })
261 router.ssr = {
262 manifest: {
263 routes: {
264 [rootRoute.id]: {
265 scripts: [clientEntryAsset],
266 },
267 },
268 },
269 }
270β
271 await router.load()
272β
273 const html = ReactDOMServer.renderToString(
274 <RouterProvider router={router} />,
275 )
276 const contentIndex = html.indexOf('<main data-testid="content">')
277 const scriptIndex = html.indexOf('src="/entry.js"')
278β
279 expect(contentIndex).toBeGreaterThan(-1)
280 expect(scriptIndex).toBeGreaterThan(contentIndex)
281 expect(html).not.toContain('client-entry')
282 })
283β
284 test('client renders scripts with attributes (including async/defer)', async () => {
285 const rootRoute = createRootRoute({
286 scripts: () => [
287 {
288 src: 'script.js',
289 async: true,
290 crossOrigin: 'anonymous',
291 },
292 ],
293 component: () => {
294 return (
295 <div>
296 <div data-testid="async-root">root</div>
297 <Outlet />
298 <Scripts />
299 </div>
300 )
301 },
302 })
303β
304 const indexRoute = createRoute({
305 path: '/',
306 getParentRoute: () => rootRoute,
307 component: () => {
308 return <div data-testid="async-index">index</div>
309 },
310 })
311β
312 // Clear head and any leftover body scripts between tests.
313 document.head.innerHTML = ''
314 document.querySelectorAll('body script').forEach((s) => s.remove())
315β
316 const router = createRouter({
317 history: createMemoryHistory({
318 initialEntries: ['/'],
319 }),
320 routeTree: rootRoute.addChildren([indexRoute]),
321 isServer: false, // Client-side rendering
322 })
323β
324 await router.load()
325β
326 await act(() => render(<RouterProvider router={router} />))
327β
328 expect(await screen.findByTestId('async-root')).toBeInTheDocument()
329β
330 const script = document.querySelector('script[src="script.js"]')
331 expect(script).toBeTruthy()
332β
333 // Attributes are preserved on the client.
334 expect(script?.getAttribute('src')).toBe('script.js')
335 expect(script?.hasAttribute('async')).toBe(true)
336 expect(script?.getAttribute('crossorigin')).toBe('anonymous')
337 })
338})
339β
340describe('ssr HeadContent', () => {
341 test('renders descendant assets during a data-only hydration handoff', async () => {
342 const rootRoute = createRootRoute({})
343 const dataOnlyRoute = createRoute({
344 getParentRoute: () => rootRoute,
345 path: '/report',
346 ssr: 'data-only',
347 loader: () => 'report',
348 })
349 const childRoute = createRoute({
350 getParentRoute: () => dataOnlyRoute,
351 path: '/details',
352 loader: () => 'details',
353 head: () => ({
354 meta: [{ name: 'data-only-child', content: 'visible' }],
355 links: [{ rel: 'preload', href: '/data-only-head-link.js' }],
356 styles: [
357 {
358 id: 'data-only-route-style',
359 children: '.data-only-child { color: green }',
360 },
361 ],
362 scripts: [
363 {
364 id: 'data-only-head-script',
365 type: 'application/json',
366 children: '{"source":"head"}',
367 },
368 ],
369 }),
370 scripts: () => [
371 {
372 id: 'data-only-body-script',
373 type: 'application/json',
374 children: '{"source":"body"}',
375 },
376 ],
377 })
378 const router = createRouter({
379 history: createMemoryHistory({
380 initialEntries: ['/report/details'],
381 }),
382 routeTree: rootRoute.addChildren([
383 dataOnlyRoute.addChildren([childRoute]),
384 ]),
385 })
386 const matches = router.matchRoutes(router.latestLocation)
387 window.$_TSR = {
388 router: {
389 dehydratedData: {},
390 manifest: {
391 routes: {
392 [childRoute.id]: {
393 css: ['/data-only-manifest.css'],
394 preloads: ['/data-only-manifest.js'],
395 scripts: [
396 {
397 attrs: {
398 id: 'data-only-manifest-script',
399 type: 'application/json',
400 },
401 children: '{"source":"manifest"}',
402 },
403 ],
404 },
405 },
406 },
407 matches: matches.map((match, index) => ({
408 i: dehydrateSsrMatchId(match.id),
409 s: 'success',
410 ssr: index === 1 ? 'data-only' : true,
411 l: index ? (index === 1 ? 'report' : 'details') : undefined,
412 u: Date.now(),
413 })),
414 },
415 h: vi.fn(),
416 e: vi.fn(),
417 c: vi.fn(),
418 p: vi.fn(),
419 buffer: [],
420 }
421β
422 await hydrate(router)
423β
424 expect(router.state.matches.map((match) => match.status)).toEqual([
425 'success',
426 'pending',
427 'success',
428 ])
429 render(
430 <RouterContextProvider router={router}>
431 <HeadContent />
432 <Scripts />
433 </RouterContextProvider>,
434 )
435β
436 expect(
437 document.querySelector('meta[name="data-only-child"]'),
438 ).not.toBeNull()
439 expect(
440 document.querySelector('link[href="/data-only-head-link.js"]'),
441 ).not.toBeNull()
442 expect(document.querySelector('#data-only-route-style')).not.toBeNull()
443 expect(document.querySelector('#data-only-head-script')).not.toBeNull()
444 expect(document.querySelector('#data-only-body-script')).not.toBeNull()
445 expect(
446 document.querySelector('link[href="/data-only-manifest.css"]'),
447 ).not.toBeNull()
448 expect(
449 document.querySelector('link[href="/data-only-manifest.js"]'),
450 ).not.toBeNull()
451 expect(document.querySelector('#data-only-manifest-script')).not.toBeNull()
452 })
453β
454 test('derives title, dedupes meta, and allows non-loader HeadContent', async () => {
455 const rootRoute = createRootRoute({
456 loader: () =>
457 new Promise((r) => setTimeout(r, 1)).then(() => ({
458 description: 'Root',
459 })),
460 head: ({ loaderData }) => {
461 return {
462 meta: [
463 {
464 title: 'Root',
465 },
466 {
467 name: 'description',
468 content: loaderData?.description,
469 },
470 {
471 name: 'image',
472 content: 'image.jpg',
473 },
474 {
475 property: 'og:image',
476 content: 'root-image.jpg',
477 },
478 {
479 property: 'og:description',
480 content: 'Root description',
481 },
482 ],
483 }
484 },
485 component: () => {
486 return <HeadContent />
487 },
488 })
489β
490 const indexRoute = createRoute({
491 path: '/',
492 getParentRoute: () => rootRoute,
493 loader: () =>
494 new Promise((r) => setTimeout(r, 2)).then(() => ({
495 description: 'Index',
496 })),
497 head: ({ loaderData }) => {
498 return {
499 meta: [
500 {
501 title: 'Index',
502 },
503 {
504 name: 'description',
505 content: loaderData?.description,
506 },
507 {
508 name: 'last-modified',
509 content: '2021-10-10',
510 },
511 {
512 property: 'og:image',
513 content: 'index-image.jpg',
514 },
515 ],
516 }
517 },
518 })
519β
520 const router = createRouter({
521 history: createMemoryHistory({
522 initialEntries: ['/'],
523 }),
524 routeTree: rootRoute.addChildren([indexRoute]),
525 isServer: true,
526 })
527β
528 await router.load()
529β
530 expect(router.state.matches.map((d) => d.meta).flat(1)).toEqual([
531 { title: 'Root' },
532 { name: 'description', content: 'Root' },
533 { name: 'image', content: 'image.jpg' },
534 { property: 'og:image', content: 'root-image.jpg' },
535 { property: 'og:description', content: 'Root description' },
536 { title: 'Index' },
537 { name: 'description', content: 'Index' },
538 { name: 'last-modified', content: '2021-10-10' },
539 { property: 'og:image', content: 'index-image.jpg' },
540 ])
541β
542 const html = ReactDOMServer.renderToString(
543 <RouterProvider router={router} />,
544 )
545 expect(html).toEqual(
546 `<title>Index</title><meta name="image" content="image.jpg"/><meta property="og:description" content="Root description"/><meta name="description" content="Index"/><meta name="last-modified" content="2021-10-10"/><meta property="og:image" content="index-image.jpg"/>`,
547 )
548 })
549β
550 test('keeps manifest stylesheet links mounted when history state changes', async () => {
551 const history = createTestBrowserHistory()
552 const stylesheetHref = '/history-state.css'
553β
554 const rootRoute = createRootRoute({
555 component: () => {
556 return (
557 <>
558 {createPortal(<HeadContent />, document.head)}
559 <button
560 onClick={() => {
561 window.history.replaceState(
562 { slideId: 'slide-2' },
563 '',
564 window.location.href,
565 )
566 }}
567 >
568 Replace state
569 </button>
570 <Outlet />
571 </>
572 )
573 },
574 })
575β
576 const indexRoute = createRoute({
577 path: '/',
578 getParentRoute: () => rootRoute,
579 component: () => <div>Index</div>,
580 })
581β
582 const router = createRouter({
583 history,
584 routeTree: rootRoute.addChildren([indexRoute]),
585 })
586β
587 router.ssr = {
588 manifest: createTestManifest(rootRoute.id, {
589 stylesheetHref,
590 }),
591 }
592β
593 await router.load()
594β
595 await act(() => render(<RouterProvider router={router} />))
596β
597 const getStylesheetLink = () =>
598 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find(
599 (link) => link.getAttribute('href') === stylesheetHref,
600 )
601β
602 await waitFor(() => {
603 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
604 })
605β
606 const initialLink = getStylesheetLink()
607 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
608β
609 fireEvent.click(screen.getByRole('button', { name: 'Replace state' }))
610β
611 await waitFor(() => {
612 expect(router.state.location.state).toMatchObject({
613 slideId: 'slide-2',
614 })
615 })
616β
617 expect(getStylesheetLink()).toBe(initialLink)
618 expect(
619 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(
620 (link) => link.getAttribute('href') === stylesheetHref,
621 ),
622 ).toHaveLength(1)
623 })
624β
625 test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => {
626 const history = createTestBrowserHistory()
627 const stylesheetHref = '/asset-cross-origin.css'
628 const preloadHref = '/asset-cross-origin.js'
629β
630 const rootRoute = createRootRoute({
631 component: () => {
632 return (
633 <>
634 {createPortal(
635 <HeadContent
636 assetCrossOrigin={{
637 script: 'anonymous',
638 stylesheet: 'use-credentials',
639 }}
640 />,
641 document.head,
642 )}
643 <Outlet />
644 </>
645 )
646 },
647 })
648β
649 const indexRoute = createRoute({
650 path: '/',
651 getParentRoute: () => rootRoute,
652 component: () => <div>Index</div>,
653 })
654β
655 const router = createRouter({
656 history,
657 routeTree: rootRoute.addChildren([indexRoute]),
658 })
659β
660 router.ssr = {
661 manifest: createTestManifest(rootRoute.id, {
662 stylesheetHref,
663 preloadHref,
664 }),
665 }
666β
667 await router.load()
668β
669 await act(() => render(<RouterProvider router={router} />))
670β
671 await waitFor(() => {
672 expect(
673 document.head.querySelector(
674 `link[rel="stylesheet"][href="${stylesheetHref}"]`,
675 ),
676 ).toBeTruthy()
677 expect(
678 document.head.querySelector(
679 `link[rel="modulepreload"][href="${preloadHref}"]`,
680 ),
681 ).toBeTruthy()
682 })
683β
684 expect(
685 document.head
686 .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`)
687 ?.getAttribute('crossorigin'),
688 ).toBe('use-credentials')
689 expect(
690 document.head
691 .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`)
692 ?.getAttribute('crossorigin'),
693 ).toBe('anonymous')
694 })
695β
696 test('renders runtime manifest inlineStyle', async () => {
697 const history = createTestBrowserHistory()
698β
699 const rootRoute = createRootRoute({
700 component: () => {
701 return (
702 <>
703 {createPortal(<HeadContent />, document.head)}
704 <Outlet />
705 </>
706 )
707 },
708 })
709β
710 const indexRoute = createRoute({
711 path: '/',
712 getParentRoute: () => rootRoute,
713 component: () => <div>Index</div>,
714 })
715β
716 const router = createRouter({
717 history,
718 routeTree: rootRoute.addChildren([indexRoute]),
719 })
720β
721 router.ssr = {
722 manifest: {
723 inlineStyle: {
724 attrs: { id: 'runtime-inline-style' },
725 children: '.runtime{color:red}',
726 },
727 routes: {
728 [rootRoute.id]: {},
729 },
730 },
731 }
732β
733 await router.load()
734β
735 await act(() => render(<RouterProvider router={router} />))
736β
737 await waitFor(() => {
738 expect(
739 document.head.querySelector('style#runtime-inline-style'),
740 ).toBeTruthy()
741 })
742β
743 expect(
744 document.head.querySelector('style#runtime-inline-style')?.textContent,
745 ).toBe('.runtime{color:red}')
746 })
747β
748 test('renders preload as script links for iife manifest preloads', async () => {
749 const history = createTestBrowserHistory()
750 const preloadHref = '/iife-preload.js'
751β
752 const rootRoute = createRootRoute({
753 component: () => {
754 return (
755 <>
756 {createPortal(<HeadContent />, document.head)}
757 <Outlet />
758 </>
759 )
760 },
761 })
762β
763 const indexRoute = createRoute({
764 path: '/',
765 getParentRoute: () => rootRoute,
766 component: () => <div>Index</div>,
767 })
768β
769 const router = createRouter({
770 history,
771 routeTree: rootRoute.addChildren([indexRoute]),
772 })
773β
774 router.ssr = {
775 manifest: createTestManifest(rootRoute.id, {
776 preloadHref,
777 scriptFormat: 'iife',
778 }),
779 }
780β
781 await router.load()
782β
783 await act(() => render(<RouterProvider router={router} />))
784β
785 await waitFor(() => {
786 expect(
787 document.head.querySelector(
788 `link[rel="preload"][as="script"][href="${preloadHref}"]`,
789 ),
790 ).toBeTruthy()
791 })
792β
793 expect(
794 document.head.querySelector(
795 `link[rel="modulepreload"][href="${preloadHref}"]`,
796 ),
797 ).toBeFalsy()
798 })
799β
800 test('assetCrossOrigin overrides manifest crossOrigin values', async () => {
801 const history = createTestBrowserHistory()
802 const stylesheetHref = '/override-cross-origin.css'
803 const preloadHref = '/override-cross-origin.js'
804β
805 const rootRoute = createRootRoute({
806 component: () => {
807 return (
808 <>
809 {createPortal(
810 <HeadContent assetCrossOrigin="anonymous" />,
811 document.head,
812 )}
813 <Outlet />
814 </>
815 )
816 },
817 })
818β
819 const indexRoute = createRoute({
820 path: '/',
821 getParentRoute: () => rootRoute,
822 component: () => <div>Index</div>,
823 })
824β
825 const router = createRouter({
826 history,
827 routeTree: rootRoute.addChildren([indexRoute]),
828 })
829β
830 router.ssr = {
831 manifest: {
832 routes: {
833 [rootRoute.id]: {
834 preloads: [
835 { href: preloadHref, crossOrigin: 'use-credentials' as const },
836 ],
837 css: [
838 {
839 href: stylesheetHref,
840 crossOrigin: 'use-credentials',
841 },
842 ],
843 },
844 },
845 } as any,
846 }
847β
848 await router.load()
849β
850 await act(() => render(<RouterProvider router={router} />))
851β
852 await waitFor(() => {
853 expect(
854 document.head.querySelector(
855 `link[rel="stylesheet"][href="${stylesheetHref}"]`,
856 ),
857 ).toBeTruthy()
858 expect(
859 document.head.querySelector(
860 `link[rel="modulepreload"][href="${preloadHref}"]`,
861 ),
862 ).toBeTruthy()
863 })
864β
865 expect(
866 document.head
867 .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`)
868 ?.getAttribute('crossorigin'),
869 ).toBe('anonymous')
870 expect(
871 document.head
872 .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`)
873 ?.getAttribute('crossorigin'),
874 ).toBe('anonymous')
875 })
876β
877 test('keeps manifest stylesheet links mounted across repeated Link navigations', async () => {
878 const history = createTestBrowserHistory()
879 const stylesheetHref = '/repeated-nav.css'
880β
881 const rootRoute = createRootRoute({
882 component: () => {
883 return (
884 <>
885 {createPortal(<HeadContent />, document.head)}
886 <Outlet />
887 </>
888 )
889 },
890 })
891β
892 const indexRoute = createRoute({
893 path: '/',
894 getParentRoute: () => rootRoute,
895 component: () => <Link to="/about">Go to about page</Link>,
896 })
897β
898 const aboutRoute = createRoute({
899 path: '/about',
900 getParentRoute: () => rootRoute,
901 component: () => <Link to="/">Back to home</Link>,
902 })
903β
904 const router = createRouter({
905 history,
906 routeTree: rootRoute.addChildren([indexRoute, aboutRoute]),
907 })
908β
909 router.ssr = {
910 manifest: createTestManifest(rootRoute.id, {
911 stylesheetHref,
912 }),
913 }
914β
915 await router.load()
916β
917 await act(() => render(<RouterProvider router={router} />))
918β
919 const getStylesheetLink = () =>
920 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find(
921 (link) => link.getAttribute('href') === stylesheetHref,
922 )
923β
924 await waitFor(() => {
925 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
926 })
927β
928 const initialLink = getStylesheetLink()
929 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
930β
931 for (let i = 0; i < 5; i++) {
932 fireEvent.click(screen.getByRole('link', { name: 'Go to about page' }))
933β
934 await waitFor(() => {
935 expect(router.state.location.pathname).toBe('/about')
936 })
937β
938 await screen.findByRole('link', { name: 'Back to home' })
939β
940 fireEvent.click(screen.getByRole('link', { name: 'Back to home' }))
941β
942 await waitFor(() => {
943 expect(router.state.location.pathname).toBe('/')
944 })
945β
946 await screen.findByRole('link', { name: 'Go to about page' })
947 }
948β
949 expect(getStylesheetLink()).toBe(initialLink)
950 expect(
951 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(
952 (link) => link.getAttribute('href') === stylesheetHref,
953 ),
954 ).toHaveLength(1)
955 })
956β
957 test('does not render retained descendant assets past a terminal parent boundary', async () => {
958 let failParent = false
959 const childHeadScript = '{"source":"child-head"}'
960 const childBodyScript = '{"source":"child-body"}'
961 const childManifestScript = '{"source":"child-manifest"}'
962 const childPreload = '/terminal-child-preload.js'
963 const childHeadLink = '/terminal-child-head-link.js'
964 const rootRoute = createRootRoute({
965 component: () => (
966 <>
967 {createPortal(<HeadContent />, document.head)}
968 <Outlet />
969 <Scripts />
970 </>
971 ),
972 })
973 const parentRoute = createRoute({
974 getParentRoute: () => rootRoute,
975 path: '/parent',
976 shouldReload: true,
977 loader: () => {
978 if (failParent) {
979 throw new Error('parent failed')
980 }
981 },
982 component: Outlet,
983 errorComponent: () => <div>Parent error</div>,
984 })
985 const childRoute = createRoute({
986 getParentRoute: () => parentRoute,
987 path: '/child',
988 head: () => ({
989 meta: [{ name: 'terminal-child', content: 'visible' }],
990 links: [{ rel: 'preload', href: childHeadLink }],
991 styles: [{ children: '.terminal-child { color: red }' }],
992 scripts: [{ type: 'application/ld+json', children: childHeadScript }],
993 }),
994 scripts: () => [
995 { type: 'application/ld+json', children: childBodyScript },
996 ],
997 component: () => <div>Child content</div>,
998 })
999 const router = createRouter({
1000 history: createMemoryHistory({ initialEntries: ['/parent/child'] }),
1001 routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]),
1002 })
1003 router.ssr = {
1004 manifest: {
1005 routes: {
1006 [childRoute.id]: {
1007 preloads: [childPreload],
1008 scripts: [
1009 {
1010 attrs: { type: 'application/ld+json' },
1011 children: childManifestScript,
1012 },
1013 ],
1014 },
1015 },
1016 },
1017 }
1018β
1019 await router.load()
1020 await act(() => render(<RouterProvider router={router} />))
1021β
1022 await waitFor(() => {
1023 expect(
1024 document.head.querySelector('meta[name="terminal-child"]'),
1025 ).not.toBeNull()
1026 expect(
1027 document.head.querySelector(`link[href="${childPreload}"]`),
1028 ).not.toBeNull()
1029 expect(
1030 document.head.querySelector(`link[href="${childHeadLink}"]`),
1031 ).not.toBeNull()
1032 expect(document.head.textContent).toContain(
1033 '.terminal-child { color: red }',
1034 )
1035 expect(document.documentElement.textContent).toContain(childHeadScript)
1036 expect(document.documentElement.textContent).toContain(childBodyScript)
1037 expect(document.documentElement.textContent).toContain(
1038 childManifestScript,
1039 )
1040 })
1041β
1042 failParent = true
1043 await act(() => router.invalidate())
1044 await screen.findByText('Parent error')
1045β
1046 expect(router.state.matches).toHaveLength(3)
1047 expect(router.state.matches[1]).toMatchObject({
1048 routeId: parentRoute.id,
1049 status: 'error',
1050 })
1051 expect(router.state.matches[2]).toMatchObject({
1052 routeId: childRoute.id,
1053 meta: [{ name: 'terminal-child', content: 'visible' }],
1054 scripts: [{ type: 'application/ld+json', children: childBodyScript }],
1055 })
1056 await waitFor(() => {
1057 expect(
1058 document.head.querySelector('meta[name="terminal-child"]'),
1059 ).toBeNull()
1060 expect(
1061 document.head.querySelector(`link[href="${childPreload}"]`),
1062 ).toBeNull()
1063 expect(
1064 document.head.querySelector(`link[href="${childHeadLink}"]`),
1065 ).toBeNull()
1066 expect(document.head.textContent).not.toContain(
1067 '.terminal-child { color: red }',
1068 )
1069 expect(document.documentElement.textContent).not.toContain(
1070 childHeadScript,
1071 )
1072 expect(document.documentElement.textContent).not.toContain(
1073 childBodyScript,
1074 )
1075 expect(document.documentElement.textContent).not.toContain(
1076 childManifestScript,
1077 )
1078 })
1079 })
1080})
1081β
1082describe('data script rendering', () => {
1083 test('data script renders content on server (SSR)', async () => {
1084 const jsonLd = JSON.stringify({
1085 '@context': 'https://schema.org',
1086 '@type': 'Article',
1087 headline: 'Test Article',
1088 })
1089β
1090 const rootRoute = createRootRoute({
1091 scripts: () => [
1092 {
1093 type: 'application/ld+json',
1094 children: jsonLd,
1095 },
1096 ],
1097 component: () => {
1098 return (
1099 <div>
1100 <div data-testid="ssr-root">root</div>
1101 <Outlet />
1102 <Scripts />
1103 </div>
1104 )
1105 },
1106 })
1107β
1108 const indexRoute = createRoute({
1109 path: '/',
1110 getParentRoute: () => rootRoute,
1111 })
1112β
1113 const router = createRouter({
1114 history: createMemoryHistory({
1115 initialEntries: ['/'],
1116 }),
1117 routeTree: rootRoute.addChildren([indexRoute]),
1118 isServer: true,
1119 })
1120β
1121 await router.load()
1122β
1123 const html = ReactDOMServer.renderToString(
1124 <RouterProvider router={router} />,
1125 )
1126β
1127 expect(html).toContain('application/ld+json')
1128 expect(html).toContain(jsonLd)
1129 })
1130β
1131 test('data script preserves content on client', async () => {
1132 const jsonLd = JSON.stringify({
1133 '@context': 'https://schema.org',
1134 '@type': 'WebSite',
1135 name: 'Test',
1136 })
1137β
1138 const rootRoute = createRootRoute({
1139 scripts: () => [
1140 {
1141 type: 'application/ld+json',
1142 children: jsonLd,
1143 },
1144 ],
1145 component: () => {
1146 return (
1147 <div>
1148 <div data-testid="data-client-root">root</div>
1149 <Outlet />
1150 <Scripts />
1151 </div>
1152 )
1153 },
1154 })
1155β
1156 const indexRoute = createRoute({
1157 path: '/',
1158 getParentRoute: () => rootRoute,
1159 })
1160β
1161 const router = createRouter({
1162 history: createMemoryHistory({
1163 initialEntries: ['/'],
1164 }),
1165 routeTree: rootRoute.addChildren([indexRoute]),
1166 })
1167β
1168 await router.load()
1169β
1170 const { container } = await act(() =>
1171 render(<RouterProvider router={router} />),
1172 )
1173β
1174 const rootEl = container.querySelector('[data-testid="data-client-root"]')
1175 expect(rootEl).not.toBeNull()
1176β
1177 const scriptEl = container.querySelector(
1178 'script[type="application/ld+json"]',
1179 )
1180 expect(scriptEl).not.toBeNull()
1181 expect(scriptEl!.innerHTML).toBe(jsonLd)
1182 })
1183β
1184 test('executable script is injected into document.head via useEffect on client', async () => {
1185 const rootRoute = createRootRoute({
1186 scripts: () => [
1187 {
1188 children: 'console.log("hello")',
1189 },
1190 ],
1191 component: () => {
1192 return (
1193 <div>
1194 <div data-testid="exec-root">root</div>
1195 <Outlet />
1196 <Scripts />
1197 </div>
1198 )
1199 },
1200 })
1201β
1202 const indexRoute = createRoute({
1203 path: '/',
1204 getParentRoute: () => rootRoute,
1205 })
1206β
1207 const router = createRouter({
1208 history: createMemoryHistory({
1209 initialEntries: ['/'],
1210 }),
1211 routeTree: rootRoute.addChildren([indexRoute]),
1212 })
1213β
1214 await router.load()
1215β
1216 const { container } = await act(() =>
1217 render(<RouterProvider router={router} />),
1218 )
1219β
1220 const rootEl = container.querySelector('[data-testid="exec-root"]')
1221 expect(rootEl).not.toBeNull()
1222β
1223 // Executable inline scripts are injected into document.head via useEffect,
1224 // not rendered in the React tree on the client.
1225 const headScript = document.head.querySelector(
1226 'script:not([type]):not([src])',
1227 )
1228 expect(headScript).not.toBeNull()
1229 expect(headScript!.textContent).toBe('console.log("hello")')
1230 })
1231β
1232 test('module script is injected into document.head via useEffect on client', async () => {
1233 const rootRoute = createRootRoute({
1234 scripts: () => [
1235 {
1236 type: 'module',
1237 children: 'import { foo } from "./foo.js"',
1238 },
1239 ],
1240 component: () => {
1241 return (
1242 <div>
1243 <div data-testid="module-root">root</div>
1244 <Outlet />
1245 <Scripts />
1246 </div>
1247 )
1248 },
1249 })
1250β
1251 const indexRoute = createRoute({
1252 path: '/',
1253 getParentRoute: () => rootRoute,
1254 })
1255β
1256 const router = createRouter({
1257 history: createMemoryHistory({
1258 initialEntries: ['/'],
1259 }),
1260 routeTree: rootRoute.addChildren([indexRoute]),
1261 })
1262β
1263 await router.load()
1264β
1265 const { container } = await act(() =>
1266 render(<RouterProvider router={router} />),
1267 )
1268β
1269 const rootEl = container.querySelector('[data-testid="module-root"]')
1270 expect(rootEl).not.toBeNull()
1271β
1272 // Module scripts are injected into document.head via useEffect,
1273 // not rendered in the React tree on the client.
1274 const moduleScript = document.head.querySelector('script[type="module"]')
1275 expect(moduleScript).not.toBeNull()
1276 expect(moduleScript!.textContent).toBe('import { foo } from "./foo.js"')
1277 })
1278β
1279 test('application/json data script preserves content', async () => {
1280 const jsonData = JSON.stringify({ config: { theme: 'dark' } })
1281β
1282 const rootRoute = createRootRoute({
1283 scripts: () => [
1284 {
1285 type: 'application/json',
1286 children: jsonData,
1287 },
1288 ],
1289 component: () => {
1290 return (
1291 <div>
1292 <div data-testid="json-root">root</div>
1293 <Outlet />
1294 <Scripts />
1295 </div>
1296 )
1297 },
1298 })
1299β
1300 const indexRoute = createRoute({
1301 path: '/',
1302 getParentRoute: () => rootRoute,
1303 })
1304β
1305 const router = createRouter({
1306 history: createMemoryHistory({
1307 initialEntries: ['/'],
1308 }),
1309 routeTree: rootRoute.addChildren([indexRoute]),
1310 })
1311β
1312 await router.load()
1313β
1314 const { container } = await act(() =>
1315 render(<RouterProvider router={router} />),
1316 )
1317β
1318 const rootEl = container.querySelector('[data-testid="json-root"]')
1319 expect(rootEl).not.toBeNull()
1320β
1321 const scriptEl = container.querySelector('script[type="application/json"]')
1322 expect(scriptEl).not.toBeNull()
1323 expect(scriptEl!.innerHTML).toBe(jsonData)
1324 })
1325β
1326 test('data script does not duplicate into document.head', async () => {
1327 const jsonLd = JSON.stringify({
1328 '@context': 'https://schema.org',
1329 '@type': 'Organization',
1330 name: 'Test Org',
1331 })
1332β
1333 const rootRoute = createRootRoute({
1334 scripts: () => [
1335 {
1336 type: 'application/ld+json',
1337 children: jsonLd,
1338 },
1339 ],
1340 component: () => {
1341 return (
1342 <div>
1343 <div data-testid="dup-root">root</div>
1344 <Outlet />
1345 <Scripts />
1346 </div>
1347 )
1348 },
1349 })
1350β
1351 const indexRoute = createRoute({
1352 path: '/',
1353 getParentRoute: () => rootRoute,
1354 })
1355β
1356 const router = createRouter({
1357 history: createMemoryHistory({
1358 initialEntries: ['/'],
1359 }),
1360 routeTree: rootRoute.addChildren([indexRoute]),
1361 })
1362β
1363 await router.load()
1364β
1365 const { container } = await act(() =>
1366 render(<RouterProvider router={router} />),
1367 )
1368β
1369 const rootEl = container.querySelector('[data-testid="dup-root"]')
1370 expect(rootEl).not.toBeNull()
1371β
1372 // Data scripts should NOT be duplicated into document.head by useEffect
1373 const headScripts = document.head.querySelectorAll(
1374 'script[type="application/ld+json"]',
1375 )
1376 expect(headScripts.length).toBe(0)
1377β
1378 // Should only exist once in the container
1379 const containerScripts = container.querySelectorAll(
1380 'script[type="application/ld+json"]',
1381 )
1382 expect(containerScripts.length).toBe(1)
1383 expect(containerScripts[0]!.innerHTML).toBe(jsonLd)
1384 })
1385β
1386 test('empty string type is treated as executable, injected via useEffect on client', async () => {
1387 const rootRoute = createRootRoute({
1388 scripts: () => [
1389 {
1390 type: '',
1391 children: 'console.log("empty type")',
1392 },
1393 ],
1394 component: () => {
1395 return (
1396 <div>
1397 <div data-testid="empty-type-root">root</div>
1398 <Outlet />
1399 <Scripts />
1400 </div>
1401 )
1402 },
1403 })
1404β
1405 const indexRoute = createRoute({
1406 path: '/',
1407 getParentRoute: () => rootRoute,
1408 })
1409β
1410 const router = createRouter({
1411 history: createMemoryHistory({
1412 initialEntries: ['/'],
1413 }),
1414 routeTree: rootRoute.addChildren([indexRoute]),
1415 })
1416β
1417 await router.load()
1418β
1419 const { container } = await act(() =>
1420 render(<RouterProvider router={router} />),
1421 )
1422β
1423 const rootEl = container.querySelector('[data-testid="empty-type-root"]')
1424 expect(rootEl).not.toBeNull()
1425β
1426 // Empty type = text/javascript per HTML spec. Executable scripts are
1427 // injected into document.head via useEffect on the client.
1428 const scriptEl = document.head.querySelector('script[type=""]')
1429 expect(scriptEl).not.toBeNull()
1430 expect(scriptEl!.textContent).toBe('console.log("empty type")')
1431 })
1432})