Is it possible to insert html into the <Head> section of NextJS?

Viewed 28

I have a backend that returns meta tags for a specific page. I would like to insert this response into the Head section of my page component.

I can insert html into React using <div dangerouslySetInnerHTML={{__html: response.someHtml}} />.

Is it possible to do the same for the <Head> component?

1 Answers

You can create a BasePage component and render the Head component inside. This BasePage component will wrap up all the pages.

import HeadTags from "./Head";

const BasePage = (props) => {
  const {
    // you might have more props but those are related to the Heads
    children,
    title,
    metaDescription,
  } = props;
  return (
    <>
      <HeadTags
        title={title}
        metaDescription={metaDescription}
        canonicalPath={canonicalPath}
      ></HeadTags>
      // you mightadd more logic here
    </>
  );
};

You can define HeadTags components

const HeadTags = (props) => { 
  const {
    title = "Default tile",
    metaDescription = "default metaDescriptino",
  } = props;

  return (
    <Head>
      <title>{title}</title>
      {/* mobile devices by default takes the content from desktop and squueze it. But if you want it to be responsive */}
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
      <meta name="description" key="description" content={metaDescription} />
      // you could add more tags  
    </Head>
  );
};

Now since your page is wrapped by BasePage, you can pass the props to BasePage and it will pass it to HeadTags component so you will set meta data dynamically based on your backend returning metatags.

Related