I need help embedding a HubSpot contact form into my Gatsby website. HubSpot provided me with their standard JavaScript embed code, but I’m not sure about the proper way to implement it in a Gatsby React component. Here’s the code they gave me:
What’s the best approach to add this HubSpot form script to my Gatsby pages? Should I use a specific plugin or handle it differently than regular HTML sites?
I handled this recently by creating a dedicated React component for the HubSpot form. Instead of adding scripts to gatsby-browser.js, I loaded the HubSpot script dynamically within the component itself. The key is to use useEffect with an empty dependency array and check if the script is already loaded to avoid duplicates. Create a div with a unique ID, then call hbspt.forms.create targeting that specific container. This approach gives you better control over when and where the form renders, plus it’s easier to manage multiple forms on different pages. Don’t forget to add error handling in case the HubSpot script fails to load - I learned that the hard way when their CDN had issues.
i’ve done this before and ran into issues with the script loading. what worked for me was putting the script in gatsby-ssr.js and gatsby-browser.js, then just calling hbspt.forms.create in useEffect. make sure to check if hbspt exists first tho or you’ll get errors during build.
honestly just use react-helmet to inject the hubspot script into your page head, then wrap the hbspt.forms.create call in a setTimeout to make sure the script loads first. works everytime for me and way simpler than the plugin route.
The gatsby-plugin-hubspot approach is worth considering if you want something more streamlined. I integrated several HubSpot forms across different pages and found that using the plugin simplified the process significantly. After installing it, you just add your portal ID to gatsby-config.js and then use the HubspotForm component directly in your JSX. The plugin handles all the script loading and timing issues automatically, which saved me from dealing with SSR complications that other methods can cause. One thing to watch out for is form styling - HubSpot’s default CSS might conflict with your site’s styles, so you may need to override some properties. Also test the form submission thoroughly because sometimes the success redirects behave differently in Gatsby compared to regular HTML sites.