Open History to see the last commit
1import { useSelector } from '@tanstack/react-store'
2import { _getAssetMatches, deepEqual } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { Asset } from './Asset'
5import { useRouter } from './useRouter'
6import type { RouterManagedTag } from '@tanstack/router-core'
7β
8type ScriptRenderAsset = RouterManagedTag & {
9 preventScriptHoist?: boolean
10}
11β
12/**
13 * Render body script tags collected from route matches and SSR manifests.
14 * Should be placed near the end of the document body.
15 */
16export const Scripts = () => {
17 const router = useRouter()
18 const nonce = router.options.ssr?.nonce
19β
20 const getScripts = (matches: Array<any>) => {
21 matches = _getAssetMatches(matches)
22 const scripts = matches
23 .flatMap((match) => match.scripts ?? [])
24 .filter(Boolean)
25 .map(
26 ({ children, ...script }) =>
27 ({
28 tag: 'script',
29 attrs: {
30 ...script,
31 suppressHydrationWarning: true,
32 nonce,
33 },
34 children,
35 }) satisfies RouterManagedTag,
36 ) as Array<ScriptRenderAsset>
37 const manifest = router.ssr?.manifest
38β
39 if (!manifest) {
40 return scripts
41 }
42β
43 for (const match of matches) {
44 const manifestScripts = manifest.routes[match.routeId]?.scripts
45β
46 if (!manifestScripts) {
47 continue
48 }
49β
50 for (const asset of manifestScripts) {
51 scripts.push({
52 tag: 'script',
53 attrs: { ...asset.attrs, nonce },
54 children: asset.children,
55 ...(typeof asset.attrs?.src === 'string'
56 ? { preventScriptHoist: true }
57 : {}),
58 })
59 }
60 }
61β
62 return scripts
63 }
64β
65 if (isServer ?? router.isServer) {
66 const activeMatches = router.stores.matches.get()
67 const scripts = getScripts(activeMatches)
68 return renderScripts(router, scripts)
69 }
70β
71 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
72 const scripts = useSelector(router.stores.matches, getScripts, {
73 compare: deepEqual,
74 })
75β
76 return renderScripts(router, scripts)
77}
78β
79function renderScripts(
80 router: ReturnType<typeof useRouter>,
81 scripts: Array<ScriptRenderAsset>,
82) {
83 if ((isServer ?? router.isServer) && router.serverSsr) {
84 const serverBufferedScript = router.serverSsr.takeBufferedScripts()
85 if (serverBufferedScript) {
86 scripts.unshift(serverBufferedScript)
87 }
88 }
89β
90 return (
91 <>
92 {scripts.map((asset, i) => (
93 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
94 ))}
95 </>
96 )
97}