Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4import { isServer } from '@tanstack/router-core/isServer'
5import { useRouter } from './useRouter'
6import { useHydrated } from './ClientOnly'
7import type { RouterManagedTag } from '@tanstack/router-core'
8β
9const INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css'
10β
11interface ScriptAttrs {
12 [key: string]: string | boolean | undefined
13 src?: string
14 suppressHydrationWarning?: boolean
15}
16β
17const noopScriptHandler = () => {}
18β
19function setScriptAttrs(
20 script: HTMLScriptElement,
21 attrs: ScriptAttrs | undefined,
22) {
23 if (!attrs) {
24 return
25 }
26β
27 for (const [key, value] of Object.entries(attrs)) {
28 if (
29 key !== 'suppressHydrationWarning' &&
30 value !== undefined &&
31 value !== false
32 ) {
33 script.setAttribute(key, typeof value === 'boolean' ? '' : String(value))
34 }
35 }
36}
37β
38export function Asset(
39 asset: RouterManagedTag & {
40 nonce?: string
41 preventScriptHoist?: boolean
42 },
43): React.ReactElement | null {
44 const { attrs, children, nonce, preventScriptHoist } = asset
45 // React 19 compares this object by reference before assigning innerHTML.
46 const innerHTML = React.useMemo(
47 () => (children === undefined ? undefined : { __html: children }),
48 [children],
49 )
50β
51 switch (asset.tag) {
52 case 'title':
53 return (
54 <title {...attrs} suppressHydrationWarning>
55 {children}
56 </title>
57 )
58 case 'meta':
59 return <meta {...attrs} suppressHydrationWarning />
60 case 'link':
61 return (
62 <link
63 {...attrs}
64 precedence={
65 attrs?.precedence ??
66 (attrs?.rel === 'stylesheet' ? 'default' : undefined)
67 }
68 nonce={nonce}
69 suppressHydrationWarning
70 />
71 )
72 case 'style':
73 if (
74 asset.inlineCss &&
75 (process.env.TSS_INLINE_CSS_ENABLED === 'true' ||
76 (process.env.TSS_INLINE_CSS_ENABLED === undefined && isServer))
77 ) {
78 return (
79 <InlineCssStyle attrs={attrs} nonce={nonce}>
80 {children}
81 </InlineCssStyle>
82 )
83 }
84β
85 return (
86 <style {...attrs} dangerouslySetInnerHTML={innerHTML} nonce={nonce} />
87 )
88 case 'script':
89 return (
90 <Script attrs={attrs} preventScriptHoist={preventScriptHoist}>
91 {children}
92 </Script>
93 )
94 default:
95 return null
96 }
97}
98β
99function InlineCssStyle({
100 attrs,
101 children,
102 nonce,
103}: {
104 attrs?: Record<string, any>
105 children?: RouterManagedTag['children']
106 nonce?: string
107}) {
108 const isInlineCssPlaceholder = children === undefined
109 const [hydratedInlineCss] = React.useState(() => {
110 if (!isInlineCssPlaceholder || typeof document === 'undefined') {
111 return undefined
112 }
113β
114 return (
115 document.querySelector<HTMLStyleElement>(
116 `style[${INLINE_CSS_HYDRATION_ATTR}]`,
117 )?.textContent ?? undefined
118 )
119 })
120 const html = isInlineCssPlaceholder
121 ? (hydratedInlineCss ?? '')
122 : (children ?? '')
123 const innerHTML = React.useMemo(() => ({ __html: html }), [html])
124β
125 return (
126 <style
127 {...attrs}
128 {...{ [INLINE_CSS_HYDRATION_ATTR]: '' }}
129 dangerouslySetInnerHTML={innerHTML}
130 nonce={nonce}
131 suppressHydrationWarning
132 />
133 )
134}
135β
136function Script({
137 attrs,
138 children,
139 preventScriptHoist,
140}: {
141 attrs?: ScriptAttrs
142 children?: string
143 preventScriptHoist?: boolean
144}) {
145 const router = useRouter()
146 const hydrated = useHydrated()
147 const innerHTML = React.useMemo(
148 () => (children === undefined ? undefined : { __html: children }),
149 [children],
150 )
151 const dataScript =
152 typeof attrs?.type === 'string' &&
153 attrs.type !== '' &&
154 attrs.type !== 'text/javascript' &&
155 attrs.type !== 'module'
156β
157 if (
158 process.env.NODE_ENV !== 'production' &&
159 attrs?.src &&
160 typeof children === 'string' &&
161 children.trim().length
162 ) {
163 console.warn(
164 '[TanStack Router] <Script> received both `src` and `children`. The `children` content will be ignored. Remove `children` or remove `src`.',
165 )
166 }
167β
168 React.useEffect(() => {
169 if (dataScript) {
170 return
171 }
172β
173 if (attrs?.src) {
174 // Anchors resolve relative URLs and preserve invalid URLs without throwing.
175 const link = document.createElement('a')
176 link.href = attrs.src
177 const normSrc = link.href
178 for (const el of document.scripts) {
179 if (el.src === normSrc) {
180 return
181 }
182 }
183β
184 const script = document.createElement('script')
185β
186 setScriptAttrs(script, attrs)
187β
188 document.head.appendChild(script)
189β
190 return () => script.remove()
191 }
192β
193 if (typeof children === 'string') {
194 const typeAttr =
195 typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'
196 const nonceAttr =
197 typeof attrs?.nonce === 'string' ? attrs.nonce : undefined
198 for (const el of document.scripts) {
199 if (el.hasAttribute('src')) {
200 continue
201 }
202β
203 const sType = el.getAttribute('type') ?? 'text/javascript'
204 const sNonce = el.getAttribute('nonce') ?? undefined
205 if (
206 el.textContent === children &&
207 sType === typeAttr &&
208 sNonce === nonceAttr
209 ) {
210 return
211 }
212 }
213β
214 const script = document.createElement('script')
215 script.textContent = children
216 setScriptAttrs(script, attrs)
217β
218 document.head.appendChild(script)
219β
220 return () => script.remove()
221 }
222β
223 return undefined
224 }, [attrs, children, dataScript])
225β
226 // --- Server rendering ---
227 if (isServer ?? router.isServer) {
228 if (attrs?.src) {
229 if (!preventScriptHoist) {
230 return <script {...attrs} suppressHydrationWarning />
231 }
232β
233 return (
234 <script
235 {...attrs}
236 // React hoists async src scripts into <head> during SSR unless they
237 // have an event handler. Start's client entry must stay after router
238 // dehydration.
239 onLoad={noopScriptHandler}
240 suppressHydrationWarning
241 />
242 )
243 }
244β
245 if (typeof children === 'string') {
246 return (
247 <script
248 {...attrs}
249 dangerouslySetInnerHTML={innerHTML}
250 suppressHydrationWarning
251 />
252 )
253 }
254β
255 return null
256 }
257β
258 // --- Client rendering ---
259β
260 // Data scripts (e.g. application/ld+json) are rendered in the tree;
261 // the useEffect intentionally skips them.
262 if (dataScript && typeof children === 'string') {
263 return (
264 <script
265 {...attrs}
266 suppressHydrationWarning
267 dangerouslySetInnerHTML={innerHTML}
268 />
269 )
270 }
271β
272 // During hydration (before useEffect has fired), render the script element
273 // to match the server-rendered HTML and avoid structural hydration mismatches.
274 // After hydration, return null β the useEffect handles imperative injection.
275 if (!hydrated) {
276 if (attrs?.src) {
277 return <script {...attrs} suppressHydrationWarning />
278 }
279β
280 if (typeof children === 'string') {
281 return (
282 <script
283 {...attrs}
284 dangerouslySetInnerHTML={innerHTML}
285 suppressHydrationWarning
286 />
287 )
288 }
289 }
290β
291 return null
292}