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('renders manifest module preloads with low fetch priority', async () => {
551 const preloadHref = '/low-priority-module.js'
552 const rootRoute = createRootRoute({
553 component: () => <HeadContent />,
554 })
555 const indexRoute = createRoute({
556 path: '/',
557 getParentRoute: () => rootRoute,
558 })
559 const router = createRouter({
560 history: createMemoryHistory({ initialEntries: ['/'] }),
561 routeTree: rootRoute.addChildren([indexRoute]),
562 isServer: true,
563 })
564β
565 router.ssr = {
566 manifest: createTestManifest(rootRoute.id, { preloadHref }),
567 }
568β
569 await router.load()
570β
571 const html = ReactDOMServer.renderToString(
572 <RouterProvider router={router} />,
573 )
574 expect(html).toContain(
575 `<link rel="modulepreload" href="${preloadHref}" fetchPriority="low"/>`,
576 )
577 })
578β
579 test('keeps manifest stylesheet links mounted when history state changes', async () => {
580 const history = createTestBrowserHistory()
581 const stylesheetHref = '/history-state.css'
582β
583 const rootRoute = createRootRoute({
584 component: () => {
585 return (
586 <>
587 {createPortal(<HeadContent />, document.head)}
588 <button
589 onClick={() => {
590 window.history.replaceState(
591 { slideId: 'slide-2' },
592 '',
593 window.location.href,
594 )
595 }}
596 >
597 Replace state
598 </button>
599 <Outlet />
600 </>
601 )
602 },
603 })
604β
605 const indexRoute = createRoute({
606 path: '/',
607 getParentRoute: () => rootRoute,
608 component: () => <div>Index</div>,
609 })
610β
611 const router = createRouter({
612 history,
613 routeTree: rootRoute.addChildren([indexRoute]),
614 })
615β
616 router.ssr = {
617 manifest: createTestManifest(rootRoute.id, {
618 stylesheetHref,
619 }),
620 }
621β
622 await router.load()
623β
624 await act(() => render(<RouterProvider router={router} />))
625β
626 const getStylesheetLink = () =>
627 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find(
628 (link) => link.getAttribute('href') === stylesheetHref,
629 )
630β
631 await waitFor(() => {
632 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
633 })
634β
635 const initialLink = getStylesheetLink()
636 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
637β
638 fireEvent.click(screen.getByRole('button', { name: 'Replace state' }))
639β
640 await waitFor(() => {
641 expect(router.state.location.state).toMatchObject({
642 slideId: 'slide-2',
643 })
644 })
645β
646 expect(getStylesheetLink()).toBe(initialLink)
647 expect(
648 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(
649 (link) => link.getAttribute('href') === stylesheetHref,
650 ),
651 ).toHaveLength(1)
652 })
653β
654 test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => {
655 const history = createTestBrowserHistory()
656 const stylesheetHref = '/asset-cross-origin.css'
657 const preloadHref = '/asset-cross-origin.js'
658β
659 const rootRoute = createRootRoute({
660 component: () => {
661 return (
662 <>
663 {createPortal(
664 <HeadContent
665 assetCrossOrigin={{
666 script: 'anonymous',
667 stylesheet: 'use-credentials',
668 }}
669 />,
670 document.head,
671 )}
672 <Outlet />
673 </>
674 )
675 },
676 })
677β
678 const indexRoute = createRoute({
679 path: '/',
680 getParentRoute: () => rootRoute,
681 component: () => <div>Index</div>,
682 })
683β
684 const router = createRouter({
685 history,
686 routeTree: rootRoute.addChildren([indexRoute]),
687 })
688β
689 router.ssr = {
690 manifest: createTestManifest(rootRoute.id, {
691 stylesheetHref,
692 preloadHref,
693 }),
694 }
695β
696 await router.load()
697β
698 await act(() => render(<RouterProvider router={router} />))
699β
700 await waitFor(() => {
701 expect(
702 document.head.querySelector(
703 `link[rel="stylesheet"][href="${stylesheetHref}"]`,
704 ),
705 ).toBeTruthy()
706 expect(
707 document.head.querySelector(
708 `link[rel="modulepreload"][href="${preloadHref}"]`,
709 ),
710 ).toBeTruthy()
711 })
712β
713 expect(
714 document.head
715 .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`)
716 ?.getAttribute('crossorigin'),
717 ).toBe('use-credentials')
718 expect(
719 document.head
720 .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`)
721 ?.getAttribute('crossorigin'),
722 ).toBe('anonymous')
723 })
724β
725 test('renders runtime manifest inlineStyle', async () => {
726 const history = createTestBrowserHistory()
727β
728 const rootRoute = createRootRoute({
729 component: () => {
730 return (
731 <>
732 {createPortal(<HeadContent />, document.head)}
733 <Outlet />
734 </>
735 )
736 },
737 })
738β
739 const indexRoute = createRoute({
740 path: '/',
741 getParentRoute: () => rootRoute,
742 component: () => <div>Index</div>,
743 })
744β
745 const router = createRouter({
746 history,
747 routeTree: rootRoute.addChildren([indexRoute]),
748 })
749β
750 router.ssr = {
751 manifest: {
752 inlineStyle: {
753 attrs: { id: 'runtime-inline-style' },
754 children: '.runtime{color:red}',
755 },
756 routes: {
757 [rootRoute.id]: {},
758 },
759 },
760 }
761β
762 await router.load()
763β
764 await act(() => render(<RouterProvider router={router} />))
765β
766 await waitFor(() => {
767 expect(
768 document.head.querySelector('style#runtime-inline-style'),
769 ).toBeTruthy()
770 })
771β
772 expect(
773 document.head.querySelector('style#runtime-inline-style')?.textContent,
774 ).toBe('.runtime{color:red}')
775 })
776β
777 test('renders iife manifest preloads as low priority script links', async () => {
778 const history = createTestBrowserHistory()
779 const preloadHref = '/iife-preload.js'
780β
781 const rootRoute = createRootRoute({
782 component: () => {
783 return (
784 <>
785 {createPortal(<HeadContent />, document.head)}
786 <Outlet />
787 </>
788 )
789 },
790 })
791β
792 const indexRoute = createRoute({
793 path: '/',
794 getParentRoute: () => rootRoute,
795 component: () => <div>Index</div>,
796 })
797β
798 const router = createRouter({
799 history,
800 routeTree: rootRoute.addChildren([indexRoute]),
801 })
802β
803 router.ssr = {
804 manifest: createTestManifest(rootRoute.id, {
805 preloadHref,
806 scriptFormat: 'iife',
807 }),
808 }
809β
810 await router.load()
811β
812 await act(() => render(<RouterProvider router={router} />))
813β
814 await waitFor(() => {
815 expect(
816 document.head.querySelector(
817 `link[rel="preload"][as="script"][href="${preloadHref}"]`,
818 ),
819 ).toBeTruthy()
820 })
821β
822 expect(
823 document.head.querySelector(
824 `link[rel="modulepreload"][href="${preloadHref}"]`,
825 ),
826 ).toBeFalsy()
827 expect(
828 document.head
829 .querySelector(
830 `link[rel="preload"][as="script"][href="${preloadHref}"]`,
831 )
832 ?.getAttribute('fetchpriority'),
833 ).toBe('low')
834 })
835β
836 test('assetCrossOrigin overrides manifest crossOrigin values', async () => {
837 const history = createTestBrowserHistory()
838 const stylesheetHref = '/override-cross-origin.css'
839 const preloadHref = '/override-cross-origin.js'
840β
841 const rootRoute = createRootRoute({
842 component: () => {
843 return (
844 <>
845 {createPortal(
846 <HeadContent assetCrossOrigin="anonymous" />,
847 document.head,
848 )}
849 <Outlet />
850 </>
851 )
852 },
853 })
854β
855 const indexRoute = createRoute({
856 path: '/',
857 getParentRoute: () => rootRoute,
858 component: () => <div>Index</div>,
859 })
860β
861 const router = createRouter({
862 history,
863 routeTree: rootRoute.addChildren([indexRoute]),
864 })
865β
866 router.ssr = {
867 manifest: {
868 routes: {
869 [rootRoute.id]: {
870 preloads: [
871 { href: preloadHref, crossOrigin: 'use-credentials' as const },
872 ],
873 css: [
874 {
875 href: stylesheetHref,
876 crossOrigin: 'use-credentials',
877 },
878 ],
879 },
880 },
881 } as any,
882 }
883β
884 await router.load()
885β
886 await act(() => render(<RouterProvider router={router} />))
887β
888 await waitFor(() => {
889 expect(
890 document.head.querySelector(
891 `link[rel="stylesheet"][href="${stylesheetHref}"]`,
892 ),
893 ).toBeTruthy()
894 expect(
895 document.head.querySelector(
896 `link[rel="modulepreload"][href="${preloadHref}"]`,
897 ),
898 ).toBeTruthy()
899 })
900β
901 expect(
902 document.head
903 .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`)
904 ?.getAttribute('crossorigin'),
905 ).toBe('anonymous')
906 expect(
907 document.head
908 .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`)
909 ?.getAttribute('crossorigin'),
910 ).toBe('anonymous')
911 })
912β
913 test('keeps manifest stylesheet links mounted across repeated Link navigations', async () => {
914 const history = createTestBrowserHistory()
915 const stylesheetHref = '/repeated-nav.css'
916β
917 const rootRoute = createRootRoute({
918 component: () => {
919 return (
920 <>
921 {createPortal(<HeadContent />, document.head)}
922 <Outlet />
923 </>
924 )
925 },
926 })
927β
928 const indexRoute = createRoute({
929 path: '/',
930 getParentRoute: () => rootRoute,
931 component: () => <Link to="/about">Go to about page</Link>,
932 })
933β
934 const aboutRoute = createRoute({
935 path: '/about',
936 getParentRoute: () => rootRoute,
937 component: () => <Link to="/">Back to home</Link>,
938 })
939β
940 const router = createRouter({
941 history,
942 routeTree: rootRoute.addChildren([indexRoute, aboutRoute]),
943 })
944β
945 router.ssr = {
946 manifest: createTestManifest(rootRoute.id, {
947 stylesheetHref,
948 }),
949 }
950β
951 await router.load()
952β
953 await act(() => render(<RouterProvider router={router} />))
954β
955 const getStylesheetLink = () =>
956 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find(
957 (link) => link.getAttribute('href') === stylesheetHref,
958 )
959β
960 await waitFor(() => {
961 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
962 })
963β
964 const initialLink = getStylesheetLink()
965 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
966β
967 for (let i = 0; i < 5; i++) {
968 fireEvent.click(screen.getByRole('link', { name: 'Go to about page' }))
969β
970 await waitFor(() => {
971 expect(router.state.location.pathname).toBe('/about')
972 })
973β
974 await screen.findByRole('link', { name: 'Back to home' })
975β
976 fireEvent.click(screen.getByRole('link', { name: 'Back to home' }))
977β
978 await waitFor(() => {
979 expect(router.state.location.pathname).toBe('/')
980 })
981β
982 await screen.findByRole('link', { name: 'Go to about page' })
983 }
984β
985 expect(getStylesheetLink()).toBe(initialLink)
986 expect(
987 Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(
988 (link) => link.getAttribute('href') === stylesheetHref,
989 ),
990 ).toHaveLength(1)
991 })
992β
993 test('does not render retained descendant assets past a terminal parent boundary', async () => {
994 let failParent = false
995 const childHeadScript = '{"source":"child-head"}'
996 const childBodyScript = '{"source":"child-body"}'
997 const childManifestScript = '{"source":"child-manifest"}'
998 const childPreload = '/terminal-child-preload.js'
999 const childHeadLink = '/terminal-child-head-link.js'
1000 const rootRoute = createRootRoute({
1001 component: () => (
1002 <>
1003 {createPortal(<HeadContent />, document.head)}
1004 <Outlet />
1005 <Scripts />
1006 </>
1007 ),
1008 })
1009 const parentRoute = createRoute({
1010 getParentRoute: () => rootRoute,
1011 path: '/parent',
1012 shouldReload: true,
1013 loader: () => {
1014 if (failParent) {
1015 throw new Error('parent failed')
1016 }
1017 },
1018 component: Outlet,
1019 errorComponent: () => <div>Parent error</div>,
1020 })
1021 const childRoute = createRoute({
1022 getParentRoute: () => parentRoute,
1023 path: '/child',
1024 head: () => ({
1025 meta: [{ name: 'terminal-child', content: 'visible' }],
1026 links: [{ rel: 'preload', href: childHeadLink }],
1027 styles: [{ children: '.terminal-child { color: red }' }],
1028 scripts: [{ type: 'application/ld+json', children: childHeadScript }],
1029 }),
1030 scripts: () => [
1031 { type: 'application/ld+json', children: childBodyScript },
1032 ],
1033 component: () => <div>Child content</div>,
1034 })
1035 const router = createRouter({
1036 history: createMemoryHistory({ initialEntries: ['/parent/child'] }),
1037 routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]),
1038 })
1039 router.ssr = {
1040 manifest: {
1041 routes: {
1042 [childRoute.id]: {
1043 preloads: [childPreload],
1044 scripts: [
1045 {
1046 attrs: { type: 'application/ld+json' },
1047 children: childManifestScript,
1048 },
1049 ],
1050 },
1051 },
1052 },
1053 }
1054β
1055 await router.load()
1056 await act(() => render(<RouterProvider router={router} />))
1057β
1058 await waitFor(() => {
1059 expect(
1060 document.head.querySelector('meta[name="terminal-child"]'),
1061 ).not.toBeNull()
1062 expect(
1063 document.head.querySelector(`link[href="${childPreload}"]`),
1064 ).not.toBeNull()
1065 expect(
1066 document.head.querySelector(`link[href="${childHeadLink}"]`),
1067 ).not.toBeNull()
1068 expect(document.head.textContent).toContain(
1069 '.terminal-child { color: red }',
1070 )
1071 expect(document.documentElement.textContent).toContain(childHeadScript)
1072 expect(document.documentElement.textContent).toContain(childBodyScript)
1073 expect(document.documentElement.textContent).toContain(
1074 childManifestScript,
1075 )
1076 })
1077β
1078 failParent = true
1079 await act(() => router.invalidate())
1080 await screen.findByText('Parent error')
1081β
1082 expect(router.state.matches).toHaveLength(3)
1083 expect(router.state.matches[1]).toMatchObject({
1084 routeId: parentRoute.id,
1085 status: 'error',
1086 })
1087 expect(router.state.matches[2]).toMatchObject({
1088 routeId: childRoute.id,
1089 meta: [{ name: 'terminal-child', content: 'visible' }],
1090 scripts: [{ type: 'application/ld+json', children: childBodyScript }],
1091 })
1092 await waitFor(() => {
1093 expect(
1094 document.head.querySelector('meta[name="terminal-child"]'),
1095 ).toBeNull()
1096 expect(
1097 document.head.querySelector(`link[href="${childPreload}"]`),
1098 ).toBeNull()
1099 expect(
1100 document.head.querySelector(`link[href="${childHeadLink}"]`),
1101 ).toBeNull()
1102 expect(document.head.textContent).not.toContain(
1103 '.terminal-child { color: red }',
1104 )
1105 expect(document.documentElement.textContent).not.toContain(
1106 childHeadScript,
1107 )
1108 expect(document.documentElement.textContent).not.toContain(
1109 childBodyScript,
1110 )
1111 expect(document.documentElement.textContent).not.toContain(
1112 childManifestScript,
1113 )
1114 })
1115 })
1116})
1117β
1118describe('data script rendering', () => {
1119 test('data script renders content on server (SSR)', async () => {
1120 const jsonLd = JSON.stringify({
1121 '@context': 'https://schema.org',
1122 '@type': 'Article',
1123 headline: 'Test Article',
1124 })
1125β
1126 const rootRoute = createRootRoute({
1127 scripts: () => [
1128 {
1129 type: 'application/ld+json',
1130 children: jsonLd,
1131 },
1132 ],
1133 component: () => {
1134 return (
1135 <div>
1136 <div data-testid="ssr-root">root</div>
1137 <Outlet />
1138 <Scripts />
1139 </div>
1140 )
1141 },
1142 })
1143β
1144 const indexRoute = createRoute({
1145 path: '/',
1146 getParentRoute: () => rootRoute,
1147 })
1148β
1149 const router = createRouter({
1150 history: createMemoryHistory({
1151 initialEntries: ['/'],
1152 }),
1153 routeTree: rootRoute.addChildren([indexRoute]),
1154 isServer: true,
1155 })
1156β
1157 await router.load()
1158β
1159 const html = ReactDOMServer.renderToString(
1160 <RouterProvider router={router} />,
1161 )
1162β
1163 expect(html).toContain('application/ld+json')
1164 expect(html).toContain(jsonLd)
1165 })
1166β
1167 test('data script preserves content on client', async () => {
1168 const jsonLd = JSON.stringify({
1169 '@context': 'https://schema.org',
1170 '@type': 'WebSite',
1171 name: 'Test',
1172 })
1173β
1174 const rootRoute = createRootRoute({
1175 scripts: () => [
1176 {
1177 type: 'application/ld+json',
1178 children: jsonLd,
1179 },
1180 ],
1181 component: () => {
1182 return (
1183 <div>
1184 <div data-testid="data-client-root">root</div>
1185 <Outlet />
1186 <Scripts />
1187 </div>
1188 )
1189 },
1190 })
1191β
1192 const indexRoute = createRoute({
1193 path: '/',
1194 getParentRoute: () => rootRoute,
1195 })
1196β
1197 const router = createRouter({
1198 history: createMemoryHistory({
1199 initialEntries: ['/'],
1200 }),
1201 routeTree: rootRoute.addChildren([indexRoute]),
1202 })
1203β
1204 await router.load()
1205β
1206 const { container } = await act(() =>
1207 render(<RouterProvider router={router} />),
1208 )
1209β
1210 const rootEl = container.querySelector('[data-testid="data-client-root"]')
1211 expect(rootEl).not.toBeNull()
1212β
1213 const scriptEl = container.querySelector(
1214 'script[type="application/ld+json"]',
1215 )
1216 expect(scriptEl).not.toBeNull()
1217 expect(scriptEl!.innerHTML).toBe(jsonLd)
1218 })
1219β
1220 test('executable script is injected into document.head via useEffect on client', async () => {
1221 const rootRoute = createRootRoute({
1222 scripts: () => [
1223 {
1224 children: 'console.log("hello")',
1225 },
1226 ],
1227 component: () => {
1228 return (
1229 <div>
1230 <div data-testid="exec-root">root</div>
1231 <Outlet />
1232 <Scripts />
1233 </div>
1234 )
1235 },
1236 })
1237β
1238 const indexRoute = createRoute({
1239 path: '/',
1240 getParentRoute: () => rootRoute,
1241 })
1242β
1243 const router = createRouter({
1244 history: createMemoryHistory({
1245 initialEntries: ['/'],
1246 }),
1247 routeTree: rootRoute.addChildren([indexRoute]),
1248 })
1249β
1250 await router.load()
1251β
1252 const { container } = await act(() =>
1253 render(<RouterProvider router={router} />),
1254 )
1255β
1256 const rootEl = container.querySelector('[data-testid="exec-root"]')
1257 expect(rootEl).not.toBeNull()
1258β
1259 // Executable inline scripts are injected into document.head via useEffect,
1260 // not rendered in the React tree on the client.
1261 const headScript = document.head.querySelector(
1262 'script:not([type]):not([src])',
1263 )
1264 expect(headScript).not.toBeNull()
1265 expect(headScript!.textContent).toBe('console.log("hello")')
1266 })
1267β
1268 test('module script is injected into document.head via useEffect on client', async () => {
1269 const rootRoute = createRootRoute({
1270 scripts: () => [
1271 {
1272 type: 'module',
1273 children: 'import { foo } from "./foo.js"',
1274 },
1275 ],
1276 component: () => {
1277 return (
1278 <div>
1279 <div data-testid="module-root">root</div>
1280 <Outlet />
1281 <Scripts />
1282 </div>
1283 )
1284 },
1285 })
1286β
1287 const indexRoute = createRoute({
1288 path: '/',
1289 getParentRoute: () => rootRoute,
1290 })
1291β
1292 const router = createRouter({
1293 history: createMemoryHistory({
1294 initialEntries: ['/'],
1295 }),
1296 routeTree: rootRoute.addChildren([indexRoute]),
1297 })
1298β
1299 await router.load()
1300β
1301 const { container } = await act(() =>
1302 render(<RouterProvider router={router} />),
1303 )
1304β
1305 const rootEl = container.querySelector('[data-testid="module-root"]')
1306 expect(rootEl).not.toBeNull()
1307β
1308 // Module scripts are injected into document.head via useEffect,
1309 // not rendered in the React tree on the client.
1310 const moduleScript = document.head.querySelector('script[type="module"]')
1311 expect(moduleScript).not.toBeNull()
1312 expect(moduleScript!.textContent).toBe('import { foo } from "./foo.js"')
1313 })
1314β
1315 test('application/json data script preserves content', async () => {
1316 const jsonData = JSON.stringify({ config: { theme: 'dark' } })
1317β
1318 const rootRoute = createRootRoute({
1319 scripts: () => [
1320 {
1321 type: 'application/json',
1322 children: jsonData,
1323 },
1324 ],
1325 component: () => {
1326 return (
1327 <div>
1328 <div data-testid="json-root">root</div>
1329 <Outlet />
1330 <Scripts />
1331 </div>
1332 )
1333 },
1334 })
1335β
1336 const indexRoute = createRoute({
1337 path: '/',
1338 getParentRoute: () => rootRoute,
1339 })
1340β
1341 const router = createRouter({
1342 history: createMemoryHistory({
1343 initialEntries: ['/'],
1344 }),
1345 routeTree: rootRoute.addChildren([indexRoute]),
1346 })
1347β
1348 await router.load()
1349β
1350 const { container } = await act(() =>
1351 render(<RouterProvider router={router} />),
1352 )
1353β
1354 const rootEl = container.querySelector('[data-testid="json-root"]')
1355 expect(rootEl).not.toBeNull()
1356β
1357 const scriptEl = container.querySelector('script[type="application/json"]')
1358 expect(scriptEl).not.toBeNull()
1359 expect(scriptEl!.innerHTML).toBe(jsonData)
1360 })
1361β
1362 test('data script does not duplicate into document.head', async () => {
1363 const jsonLd = JSON.stringify({
1364 '@context': 'https://schema.org',
1365 '@type': 'Organization',
1366 name: 'Test Org',
1367 })
1368β
1369 const rootRoute = createRootRoute({
1370 scripts: () => [
1371 {
1372 type: 'application/ld+json',
1373 children: jsonLd,
1374 },
1375 ],
1376 component: () => {
1377 return (
1378 <div>
1379 <div data-testid="dup-root">root</div>
1380 <Outlet />
1381 <Scripts />
1382 </div>
1383 )
1384 },
1385 })
1386β
1387 const indexRoute = createRoute({
1388 path: '/',
1389 getParentRoute: () => rootRoute,
1390 })
1391β
1392 const router = createRouter({
1393 history: createMemoryHistory({
1394 initialEntries: ['/'],
1395 }),
1396 routeTree: rootRoute.addChildren([indexRoute]),
1397 })
1398β
1399 await router.load()
1400β
1401 const { container } = await act(() =>
1402 render(<RouterProvider router={router} />),
1403 )
1404β
1405 const rootEl = container.querySelector('[data-testid="dup-root"]')
1406 expect(rootEl).not.toBeNull()
1407β
1408 // Data scripts should NOT be duplicated into document.head by useEffect
1409 const headScripts = document.head.querySelectorAll(
1410 'script[type="application/ld+json"]',
1411 )
1412 expect(headScripts.length).toBe(0)
1413β
1414 // Should only exist once in the container
1415 const containerScripts = container.querySelectorAll(
1416 'script[type="application/ld+json"]',
1417 )
1418 expect(containerScripts.length).toBe(1)
1419 expect(containerScripts[0]!.innerHTML).toBe(jsonLd)
1420 })
1421β
1422 test('empty string type is treated as executable, injected via useEffect on client', async () => {
1423 const rootRoute = createRootRoute({
1424 scripts: () => [
1425 {
1426 type: '',
1427 children: 'console.log("empty type")',
1428 },
1429 ],
1430 component: () => {
1431 return (
1432 <div>
1433 <div data-testid="empty-type-root">root</div>
1434 <Outlet />
1435 <Scripts />
1436 </div>
1437 )
1438 },
1439 })
1440β
1441 const indexRoute = createRoute({
1442 path: '/',
1443 getParentRoute: () => rootRoute,
1444 })
1445β
1446 const router = createRouter({
1447 history: createMemoryHistory({
1448 initialEntries: ['/'],
1449 }),
1450 routeTree: rootRoute.addChildren([indexRoute]),
1451 })
1452β
1453 await router.load()
1454β
1455 const { container } = await act(() =>
1456 render(<RouterProvider router={router} />),
1457 )
1458β
1459 const rootEl = container.querySelector('[data-testid="empty-type-root"]')
1460 expect(rootEl).not.toBeNull()
1461β
1462 // Empty type = text/javascript per HTML spec. Executable scripts are
1463 // injected into document.head via useEffect on the client.
1464 const scriptEl = document.head.querySelector('script[type=""]')
1465 expect(scriptEl).not.toBeNull()
1466 expect(scriptEl!.textContent).toBe('console.log("empty type")')
1467 })
1468})