Skip to content

[v2] Calling useHead in the client after SSR no longer updates the tags in the head but instead removes existing #530

@adamdehaven

Description

@adamdehaven

Environment

  • Operating System: Darwin
  • Node Version: v22.14.0
  • Nuxt Version: 3.16.1
  • CLI Version: 3.23.1
  • Nitro Version: 2.11.7
  • Package Manager: pnpm@10.6.2
  • Builder: -
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/github-pfsubbgy?file=app.vue

Describe the bug

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:

export default function useCustomStyles(styles: ComputedRef<string>, id?: string) {
  const componentId = id || useId()
  const computedStyles = computed((): string => {
    if (!styles.value || String(styles.value || '').trim().length === 0) {
      return ''
    }
    // wrapString just combines the values into valid CSS
    return wrapString(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().id as string)

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.

Additional context

No response

Logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions