javascriptformsnext.jshubspot

HubSpot form script in NextJS head


I'm trying to add the following script to my NextJS Head:

<script>
  hbspt.forms.create({
    region: "na1",
    portalId: "XXXXXX",
    formId: "XXXXXX"
});
</script>

Then it gives me two errors:

Error 1: Unexpected token. Did you mean {'}'} or &rbrace;?ts(1381) (for closing bracket)

Error 2: Syntax error: Unexpected token, expected "}" (for the line "region: "na1")

This is the whole indes.jsx file:

import Head from "next/head";
import styled from "styled-components";
import HeroSection from "../components/sections/HeroSection";
import OverviewSection from "../components/sections/OverviewSection";

const Wrapper = styled.div`
  margin-top: 10rem;
`;

export default function HomePage() {
  return (
    <Wrapper>
      <Head>
        <title>Code Shape - Home</title>
        <link rel="icon" href="/favicon.ico" />
        <script
          type="text/javascript"
          id="hs-script-loader"
          async
          defer
          src="//js.hs-scripts.com/8205013.js"
        ></script>
        <script
          charset="utf-8"
          type="text/javascript"
          src="//js.hsforms.net/forms/shell.js"
        ></script>
        <script>
          hbspt.forms.create(
          {
            region: "na1",
            portalId: "XXXXXX",
            formId: "XXXXXX",
          }
          );
        </script>
      </Head>
      <HeroSection />
    </Wrapper>
  );
}

The script is coming from HubSpot when generating the form, so I assumed the script code is right.


Solution

  • The code is getting escaped, try and wrap it into the dangerouslySetInnerHTML property:

      <Head>
        <script dangerouslySetInnerHTML={{ __html: `
           hbspt.forms.create({
               region: "na1",
               portalId: "XXXXXX",
               formId: "XXXXXX"
           });
         `}} />
      </Head>