Skip to content

Next/Head - return null for conditional head scripts #13658

@asherccohen

Description

@asherccohen

Feature request

When using next/head in a page we should be able to render head scripts conditionally by returning null from a custom component.

Is your feature request related to a problem? Please describe.

If a custom component that can return null (depending on its internal logic) is added as a child of Next/Head the page breaks.

Example:

<Head>
  <CustomComponent booleanProp={true} />
</Head>

Where CustomComponent is something like:

const CustomComponent = ({booleanProp}) => {

if(booleanProp){
  return <script>some js script</script>
}

return null;
};

The last 'return null' will break the page since a file called headManager.js has this logic:

  for (var i = 0, j = headCountEl.previousElementSibling; i < headCount; i++, j = j.previousElementSibling) {
    if (j.tagName.toLowerCase() === type) {
      oldTags.push(j);
    }
  }

Therefore j.tagName is undefined.

Describe the solution you'd like

I would like to be able to return null (as it's very common in react components) when my condition is not met; this will let NextJs skip the script.

Something simple like:

    if (j.tagName && j.tagName.toLowerCase() === type) {
      oldTags.push(j);
    }

As an added bonus we can log a warning for head scripts returning null.

Describe alternatives you've considered

headManager.js should handle 'null' script tags.

Metadata

Metadata

Assignees

No one assigned

    Labels

    MetadataRelated to Next.js' Metadata API.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions