You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[v2] Calling useHead in the client after SSR no longer updates the tags in the head but instead removes existing #530
Before unhead v2, the following composable would reactively update the tags inserted in the <head> when the styles: ComputedRef<string> changed in the calling component:
exportdefaultfunctionuseCustomStyles(styles: ComputedRef<string>,id?: string){constcomponentId=id||useId()constcomputedStyles=computed((): string=>{if(!styles.value||String(styles.value||'').trim().length===0){return''}// wrapString just combines the values into valid CSSreturnwrapString(styles.value,`#${componentId} {`,'}')})useHead({style: [computedStyles.value ? {key: `custom-styles-${componentId}`,id: `custom-styles-${componentId}`,innerHTML: computedStyles.value,tagPosition: 'head',tagPriority: 2000,} : {},],})return{
componentId,}}// Usage in a component:const{ componentId }=useCustomStyles(computed(()=>props.styles),useAttrs().idasstring)
Since v2, when the styles param is changed in the consuming component, the custom-styles-* entry in the head is removed (reactively); however, it is not replaced with an updated version of the tag.
Hi, a reproduction would be handy. Looking at the code I'm not exactly sure how v1 was correctly handling this, there's no way for unhead to track the reactivity side effects because you only pass the resolved value.
I'd rewrite it like so
exportdefaultfunctionuseCustomStyles(styles: ComputedRef<string>,id?: string){constcomponentId=id||useId()useHead({style: [()=>{if(!styles.value||String(styles.value||'').trim().length===0){returnundefined}// wrapString just combines the values into valid CSSreturn{key: `custom-styles-${componentId}`,id: `custom-styles-${componentId}`,innerHTML: wrapString(styles.value,`#${componentId} {`,'}'),tagPosition: 'head',tagPriority: 2000,}}],})return{
componentId,}}
Also you may consider using textContent over innerHTML if it doesn't cause issue, you'll be safer from XSS if the source is untrusted.
The code I have in the original post works in v2 when the page is initially rendered via SSR.
It's hard to show a full reproduction as the issue arises when something happens in the client that causes styles prop to change (via postMessage from outside the window via iframe parent 😬). I will try to put something together that adds a tag in the client on button click and see if I can reproduce.
The composable is called inside a MDC component, and when it re-renders in the client, the existing tag in the head is correctly removed (as the useId() changes when the component re-mounts, meaning the key changes).
If useHead is called in the client after the page is already rendered, should it actually inject a new tag into in the head?
Also you may consider using textContent over innerHTML if it doesn't cause issue, you'll be safer from XSS if the source is untrusted.
My actual implementation has a parseCustomCss utility wrapping the content to sanitize the content 😄
The only time Unhead will remove a tag is once the client renders it, so the only likely thing that is happening is:
Hydrates with valid value -> updates to null (removing the tag) -> updates to new value, a new tag with a id is generated (?)
It's possible this worked in v1 as there was an arbitrary delay when flushing the tags (around ~10ms), in v2 it just attaches to nextTick() so the renders are a lot quicker
It's possible this worked in v1 as there was an arbitrary delay when flushing the tags (around ~10ms), in v2 it just attaches to nextTick() so the renders are a lot quicker
Is there a way to make this functional in v2?
UPDATE: I added an artificial delay in the component (e.g. root of script setup await new Promise((resolve) => setTimeout(resolve, 0))) and this does indeed allow time for the render to complete as expected.
Is it possible to update my implementation, or a config setting, so that the render actually waits for the flush or something before resolving?
If I update the composable to add an artificial delay alongside computedAsync from @vueuse/core it seems to resolve the issue for me:
importtype{ComputedRef}from'vue'import{computedAsync}from'@vueuse/core'exportdefaultfunctionuseCustomStyles(styles: ComputedRef<string>,id?: string){constcomponentId=id||useId()/** * We utilize the `computedAsync` function from `@vueuse/core` to ensure the styles are applied after unhead's internal `await nextTick()` has resolved * by implementing an artificial delay. * * !IMPORTANT: This delay should only be applied in the client-side context. * * This should have no impact on the SSR/normal rendering of the parent component. */constcomputedStyles=computedAsync(async(): Promise<string|undefined>=>{if(import.meta.client){// Wait to ensure the styles are available (don't use `nextTick()` here)awaitnewPromise((resolve)=>setTimeout(resolve,0))}if(!styles.value||String(styles.value||'').trim().length===0){return}returnparseCustomCss(wrapString(styles.value,`#${componentId} {`,'}'))},// Initial stateundefined,)useHead({style: [()=>computedStyles.value ? {key: `custom-styles-${componentId}`,id: `custom-styles-${componentId}`,'data-testid': `custom-styles-${componentId}`,innerHTML: computedStyles.value,tagPosition: 'head',tagPriority: 2000,} : {},],})return{
componentId,}}
Hi,
we have found nearly the same issue. SSR useHead could not updated via SPA mode. nuxt/nuxt#33876
Environment
╭── Nuxt project info ─────────────────────────────────────────────────────╮
│ │ │
│ │ Operating system Linux 6.14.0-116036-tuxedo │
│ │ CPU 12th Gen Intel(R) Core(TM) i7-12700H (20 cores) │
│ │ Node.js version v24.9.0 │
│ │ nuxt/cli version 3.31.2 │
│ │ Package manager npm 11.6.0 │
│ │ Nuxt version 3.20.2 │
│ │ Nitro version 2.12.9 │
│ │ Builder vite 7.2.7 │
│ │ Config compatibilityDate, devtools │
│ │ Modules - │
│ │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯
universal Mode with SSR & SPA rendering
Reproduction
git clone https://github.com/sgc-fireball/nuxt3-usehead-issue
cd nuxt3-usehead-issue
npm run dev
Any useHead link that was set on server side, could not be replaced or update. In Issue #33834 was the documentation updated, but not on the nuxt website in version 3 oder 4. AND this doesn't help or fix the problem!
In one of my projects we have a the same bug with a little bit other representation. We use useServerHead and useHead, this results in an update of the Tag, BUT they will never removed!
In the Issue Report #33834 was referenced to the dispose function, but, how can i access the response from useHead in another page o0 ?
Activity
harlan-zw commentedon Mar 25, 2025
Hi, a reproduction would be handy. Looking at the code I'm not exactly sure how v1 was correctly handling this, there's no way for unhead to track the reactivity side effects because you only pass the resolved value.
I'd rewrite it like so
Also you may consider using
textContentoverinnerHTMLif it doesn't cause issue, you'll be safer from XSS if the source is untrusted.adamdehaven commentedon Mar 25, 2025
The code I have in the original post works in v2 when the page is initially rendered via SSR.
It's hard to show a full reproduction as the issue arises when something happens in the client that causes
stylesprop to change (viapostMessagefrom outside the window viaiframeparent 😬). I will try to put something together that adds a tag in the client on button click and see if I can reproduce.The composable is called inside a
MDCcomponent, and when it re-renders in the client, the existing tag in theheadis correctly removed (as theuseId()changes when the component re-mounts, meaning thekeychanges).If
useHeadis called in the client after the page is already rendered, should it actually inject a new tag into in thehead?My actual implementation has a
parseCustomCssutility wrapping the content to sanitize the content 😄harlan-zw commentedon Mar 25, 2025
The only time Unhead will remove a tag is once the client renders it, so the only likely thing that is happening is:
Hydrates with valid value -> updates to null (removing the tag) -> updates to new value, a new tag with a id is generated (?)
It's possible this worked in v1 as there was an arbitrary delay when flushing the tags (around ~10ms), in v2 it just attaches to
nextTick()so the renders are a lot quickeradamdehaven commentedon Mar 25, 2025
@harlan-zw I've updated with a reproduction:
https://stackblitz.com/edit/github-pfsubbgy?file=app.vue
adamdehaven commentedon Mar 25, 2025
Is there a way to make this functional in v2?
UPDATE: I added an artificial delay in the component (e.g. root of script setup
await new Promise((resolve) => setTimeout(resolve, 0))) and this does indeed allow time for the render to complete as expected.Is it possible to update my implementation, or a config setting, so that the render actually waits for the flush or something before resolving?
harlan-zw commentedon Mar 25, 2025
Hmm this is very strange 🤔 I'm guessing it's related to why
stylesonly updates on the second click https://stackblitz.com/edit/github-pfsubbgy-5nvqojuf?file=app.vue (may be a Nuxt core issue)adamdehaven commentedon Mar 25, 2025
If I update the composable to add an artificial delay alongside
computedAsyncfrom@vueuse/coreit seems to resolve the issue for me:harlan-zw commentedon Mar 25, 2025
Hmm nice, I'm still lost on the issue. If you're keen to find a proper solution a reproduction with just Unhead + Vue SSR may make it easier to debug https://stackblitz.com/edit/github-1ftqrmwn?file=README.md
sgc-fireball commentedon Jan 5, 2026
Hi,
we have found nearly the same issue. SSR useHead could not updated via SPA mode.
nuxt/nuxt#33876
Environment
universal Mode with SSR & SPA rendering
Reproduction
git clone https://github.com/sgc-fireball/nuxt3-usehead-issue cd nuxt3-usehead-issue npm run devOpen http://localhost:3000
watch into the chrome debugger and search alternate links.
Describe the bug
Any useHead link that was set on server side, could not be replaced or update. In Issue #33834 was the documentation updated, but not on the nuxt website in version 3 oder 4. AND this doesn't help or fix the problem!
In one of my projects we have a the same bug with a little bit other representation. We use useServerHead and useHead, this results in an update of the Tag, BUT they will never removed!
In the Issue Report #33834 was referenced to the dispose function, but, how can i access the response from useHead in another page o0 ?
fix(client): process pending patches even when dirty is false (#530)
fix(client): process pending patches even when dirty is false (#530) (#…
harlan-zw commentedon Jan 6, 2026
Fixed in v3 :) Thanks for the details.