Struggling to get your HubSpot forms to look just right on your custom website, or finding it tricky to manage submissions outside of HubSpot’s standard embeds? You’re in luck! Using npm Node Package Manager for HubSpot form integration is often the best way to gain full control over your forms’ appearance, behavior, and data handling, especially when you’re working with modern web frameworks like React, Vue, or Angular, or even robust backend systems with Node.js. This guide is your friendly walkthrough for integrating HubSpot forms with the power of npm, ensuring your lead capture strategy is as smooth and flexible as possible.
Integrating HubSpot forms with npm gives you the power to break free from HubSpot’s default styling, allowing you to match your forms perfectly with your brand’s unique look and feel. It’s about taking the solid CRM capabilities of HubSpot and pairing them with the design freedom and development flexibility that modern web development demands. We’ll explore various approaches, from direct API submissions for ultimate control to convenient React-specific npm packages that simplify the process.
Why Even Bother with NPM for HubSpot Forms?
You might be thinking, “Can’t I just copy-paste the HubSpot embed code?” And yes, you absolutely can. HubSpot provides a simple embed code that works for many basic scenarios. But here’s the thing: that embed code often comes with its own styling, can be a bit rigid to customize, and sometimes doesn’t play nicely with client-side frameworks, leading to a less-than-ideal user experience.
That’s where npm comes in. By leveraging npm packages or the HubSpot Forms API directly, you get several major benefits:
0.0 out of 5 stars (based on 0 reviews)
There are no reviews yet. Be the first one to write one. |
Amazon.com:
Check Amazon for Mastering HubSpot Forms Latest Discussions & Reviews: |
- Complete Design Freedom: You get to style your forms exactly how you want, using your existing CSS framework or custom styles, without fighting HubSpot’s default look.
- Seamless Framework Integration: If you’re building with React, Next.js, or other popular JavaScript frameworks, npm packages are designed to integrate natively, making your development workflow much smoother.
- Enhanced User Experience: Implement custom client-side validation, dynamic fields, and richer user feedback for a truly polished experience.
- Server-Side Control & Security: For sensitive data or complex logic, you can handle form submissions on your server, keeping your HubSpot API keys secure and enabling deeper integrations with other backend services.
- Version Control & Maintainability: Managing integrations through npm means they’re part of your project’s dependency management, making updates and collaboration much easier.
Method 1: The Direct API Submission – Ultimate Control
If you’re looking for the most flexibility and control, especially when you have a custom frontend and want to handle submissions from your own server, submitting directly to the HubSpot Forms API is the way to go. This method bypasses the traditional HubSpot embed script entirely and lets you send data from any form on your site straight into HubSpot.
Master Your Inbox: How to Use the Outlook HubSpot Plugin for Smarter Sales
When to Use Direct API Submission
This approach is perfect for:
- Single Page Applications SPAs: React, Vue, Angular apps where you build forms from scratch.
- Backend Services: Node.js applications that collect data and need to push it into HubSpot.
- Advanced Customization: When you need intricate form logic, multi-step forms, or want to integrate with other APIs before sending data to HubSpot.
Prerequisites
Before you start coding, you’ll need a couple of things from your HubSpot account:
- Create a HubSpot Form: Go into HubSpot
Marketing > Lead Capture > Forms
and create the form you want to integrate. You’ll need to define all the fields you plan to capture. Make sure the internal “Property Names” for these fields match what you’ll be sending. - Get Your Portal ID: You can usually find this number in the top right corner of your HubSpot dashboard when logged in.
- Get Your Form GUID Global Unique Identifier: After creating your form, open it for editing. The GUID is the long string of letters and numbers in the URL e.g.,
forms/v2/YOUR_PORTAL_ID/YOUR_FORM_GUID/
. Save this, you’ll need it. - Obtain an Access Token or API Key: For secure API interactions, HubSpot typically recommends using a Private App Access Token. You can create one in HubSpot under
Settings > Integrations > Private Apps
. While older methods might mention API keys, access tokens from private apps offer more granular control and security. You’ll need to give your private app the necessary scopes to submit forms e.g.,forms
.
Technical Steps: Submitting Data via Node.js
Let’s walk through a common scenario: submitting data from a custom HTML form on your frontend to a Node.js backend, which then sends it to HubSpot. This keeps your sensitive HubSpot credentials off the client-side.
Step 1: Create Your HubSpot Form
As mentioned, set up your form in HubSpot. Let’s say you have fields for firstname
, lastname
, and email
.
Step 2: Set up Your Node.js Server
You’ll need a simple server to act as an intermediary. We’ll use Express. Integrating HubSpot Tracking in Your Project: What’s the Deal with npm?
First, install Express and a library like axios
to make HTTP requests:
npm install express axios dotenv
Next, create a .env
file in your project root to store your HubSpot credentials securely:
HUBSPOT_PORTAL_ID=YOUR_PORTAL_ID
HUBSPOT_FORM_GUID=YOUR_FORM_GUID
HUBSPOT_ACCESS_TOKEN=YOUR_PRIVATE_APP_ACCESS_TOKEN
Now, here’s an example of your server.js
or app.js
file:
require'dotenv'.config. // Load environment variables
const express = require'express'.
const axios = require'axios'.
const app = express.
const port = 3000.
// Middleware to parse JSON bodies
app.useexpress.json.
// Enable CORS if your frontend is on a different domain
app.usereq, res, next => {
res.header'Access-Control-Allow-Origin', '*'. // Adjust as needed for production
res.header'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'.
next.
}.
app.post'/submit-hubspot-form', async req, res => {
const portalId = process.env.HUBSPOT_PORTAL_ID.
const formGuid = process.env.HUBSPOT_FORM_GUID.
const accessToken = process.env.HUBSPOT_ACCESS_TOKEN. // Using Access Token for API client
const { email, firstname, lastname } = req.body. // Data from your frontend form
// HubSpot Forms API endpoint
const hubspotApiUrl = `https://api.hsforms.com/submissions/v3/integration/submit/${portalId}/${formGuid}`.
// Construct the payload for HubSpot
const payload = {
fields:
{ name: 'email', value: email },
{ name: 'firstname', value: firstname },
{ name: 'lastname', value: lastname },
,
// Important context for HubSpot tracking and analytics
context: {
hutk: req.headers || '', // HubSpot tracking cookie
pageUri: req.headers || 'http://example.com/unknown-page', // Referrer URL
pageName: req.headers || 'Unknown Page', // Page title
},
// Optional: for GDPR compliance, if your form collects consent
// legalConsentOptions: {
// consent: {
// consentToProcess: true,
// text: "I agree to allow Example Company to store and process my personal data.",
// communications:
// {
// value: true,
// subscriptionTypeId: 999, // Replace with your actual subscription type ID
// text: "I agree to receive marketing communications.",
// },
// ,
// },
// },
}.
try {
const hubspotResponse = await axios.posthubspotApiUrl, payload, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`, // Use Access Token for authentication
},
}.
if hubspotResponse.status === 200 || hubspotResponse.status === 204 {
console.log'Form submitted successfully to HubSpot!'.
res.status200.json{ message: 'Form submitted successfully!' }.
} else {
console.error'HubSpot API Error:', hubspotResponse.data.
res.statushubspotResponse.status.json{ message: 'Failed to submit form to HubSpot.', errors: hubspotResponse.data }.
}
} catch error {
console.error'Server error submitting to HubSpot:', error.response ? error.response.data : error.message.
res.status500.json{ message: 'Internal server error.', details: error.response ? error.response.data : error.message }.
}
app.listenport, => {
console.log`Server listening at http://localhost:${port}`.
Important Notes for Direct API Submission:
* `hutk` HubSpot User Tracking Key: This cookie is crucial for HubSpot to track the user submitting the form and associate them with their browsing history. You'll need to send this from your client-side to your Node.js server, typically as a custom header, and then include it in the `context` object of your payload.
* `pageUri` and `pageName`: Also part of the `context` object, these help HubSpot correctly attribute the form submission to the page where it occurred.
* Error Handling: Make sure to handle potential API errors gracefully, both on your server and by providing feedback to your users.
* Security: Never expose your `HUBSPOT_ACCESS_TOKEN` directly in client-side code. Use environment variables and process submissions through a secure backend.
Method 2: Leveraging React-Specific NPM Packages
If you're building a React application, you're in luck! Several npm packages are designed to make integrating HubSpot forms much simpler than manually embedding scripts or building a full API submission system from scratch. These packages wrap HubSpot's functionality into React components or hooks, giving you more control and a more "React-native" feel.
# Popular React HubSpot Form NPM Packages
Let's look at a few notable ones:
1. `@ez-digital/react-hubspot-hook-form`
This is a modern package that integrates well with `react-hook-form` for robust client-side validation. It offers dynamic form fetching and highly customizable styles.
Features:
* Fetches and displays HubSpot forms dynamically based on form ID.
* Allows extensive customization of form and field styles.
* Leverages `react-hook-form` for client-side validation.
* Handles form submissions with HubSpot API integration.
* Provides feedback messages success/error.
Installation:
npm install @ez-digital/react-hubspot-hook-form react-hook-form
Usage Simplified:
Crucially, this package, like many others aiming for security, mandates that form data requests be submitted from a server, rejecting any client-side requests. This means you still need a small server-side component to securely store your `PORTAL_ID` and `HUBSPOT_API_TOKEN` and handle the actual submission.
Your server would expose an endpoint e.g., `/api/submit-hubspot-form` that receives data from your React component and then makes the secure call to HubSpot, similar to the Node.js example above.
// Example of a React component using this package conceptual
// Remember, actual API submission happens on your server, not directly from this client-side code
import React from 'react'.
import HubSpotForm from '@ez-digital/react-hubspot-hook-form'.
import '@ez-digital/react-hubspot-hook-form/style.css'. // Import default styles or create your own
const MyCustomHubspotForm = => {
// Assuming you have an API endpoint on your server to handle submissions
const onSubmit = async data => {
try {
const response = await fetch'/api/submit-hubspot-form', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringifydata,
}.
const result = await response.json.
if response.ok {
console.log'Form submitted via server:', result.
// Handle success, show a message
} else {
console.error'Server submission error:', result.
// Handle error
}
} catch error {
console.error'Network error during form submission:', error.
}.
return
<div>
<h3>Get in touch!</h3>
<HubSpotForm
portalId="YOUR_PORTAL_ID" // Should ideally be fetched from server or securely stored
formId="YOUR_FORM_GUID" // Should ideally be fetched from server or securely stored
onSubmit={onSubmit}
loadingComponent={ => <div>Loading form...</div>}
successMessage="Thanks for your submission!"
errorMessage="Oops! Something went wrong."
// ... more customization props
/>
</div>
.
}.
export default MyCustomHubspotForm.
2. `@aaronhayes/react-use-hubspot-form`
This package provides React hooks for embedding HubSpot forms, making it quite convenient for React developers.
* Embeds HubSpot forms using hooks.
* Works well with Create React App, Gatsby, and other platforms.
* Simplifies adding the HubSpot script to your document.
npm install --save @aaronhayes/react-use-hubspot-form
Usage:
import { HubspotProvider, useHubspotForm } from '@aaronhayes/react-use-hubspot-form'.
const MyFormPage = => {
const { loaded, error, formCreated } = useHubspotForm{
portalId: 'YOUR_PORTAL_ID',
formId: 'YOUR_FORM_GUID',
target: '#my-hubspot-form', // The ID of the div where the form will be rendered
}.
<h1>Fill out the form below!</h1>
{!loaded && <div>Loading HubSpot form...</div>}
{error && <div>Error loading form: {error.message}</div>}
<div id="my-hubspot-form"></div> {/* This is where the form will appear */}
const App = =>
<HubspotProvider>
<MyFormPage />
</HubspotProvider>
.
export default App.
You need to wrap your application or the relevant part with `HubspotProvider` once. This provider handles injecting the necessary HubSpot script into your document head. Then, within any component, you can use `useHubspotForm` to specify where and which HubSpot form to render.
3. `next-hubspot` for Next.js Applications
If you're specifically building with Next.js, `next-hubspot` is a tailored solution that takes advantage of Next.js features like `next/script` for optimized script loading.
npm install next-hubspot
# or pnpm add next-hubspot
# or yarn add next-hubspot
Usage in your `_app.js` or `_app.tsx` for the Provider, and a component for the form:
// pages/_app.js or _app.tsx
import { HubspotProvider } from 'next-hubspot'.
function MyApp{ Component, pageProps } {
<HubspotProvider>
<Component {...pageProps} />
</HubspotProvider>
}
export default MyApp.
// components/HubspotContactForm.js
import { useHubspotForm } from 'next-hubspot'.
const HubspotContactForm = => {
const { isFormCreated, isError, error } = useHubspotForm{
target: '#hubspot-form-wrapper',
{isError && <p>Error loading form: {error?.message}</p>}
{!isFormCreated && !isError && <p>Loading form...</p>}
<div id="hubspot-form-wrapper" />
export default HubspotContactForm.
Similar to `react-use-hubspot-form`, you wrap your app with `HubspotProvider` and then use `useHubspotForm` in your components to render forms. This package is pure ESM, so keep that in mind if you're mixing module types.
Method 3: HubSpot's Official Node.js API Client `@hubspot/api-client`
While the direct API submission Method 1 is great for forms specifically, if your Node.js application needs to interact with HubSpot in a broader sense—creating contacts, updating companies, fetching deals, or managing other CRM objects—then the official `@hubspot/api-client` npm package is your best friend.
This client simplifies making requests to HubSpot's comprehensive V3 API, handling authentication, request formatting, and response parsing for you.
# When to Use `@hubspot/api-client`
* Server-Side Logic: When you need your backend to perform complex operations in HubSpot, not just simple form submissions.
* CRM Data Management: Creating or updating contacts, companies, deals, or custom objects.
* Workflow Triggers: Initiating HubSpot workflows based on events in your application.
* Data Synchronization: Keeping data consistent between your application and HubSpot.
# Installation
It's straightforward to get this client into your project:
npm install @hubspot/api-client
# Authentication
Just like direct API submissions, you'll need an Access Token from a HubSpot Private App or an OAuth2 access token. Using a Private App is generally recommended for internal integrations as it provides a stable token.
# Basic Usage Example: Creating a Contact
Here’s how you'd use the `@hubspot/api-client` to create a new contact from your Node.js application. While this isn't a *form submission* per se, it demonstrates the client's capabilities, which you could easily integrate after processing data from a custom form on your server.
require'dotenv'.config.
const hubspot = require'@hubspot/api-client'.
const createHubSpotContact = async contactData => {
const accessToken = process.env.HUBSPOT_ACCESS_TOKEN.
// Initialize the HubSpot client
const hubspotClient = new hubspot.Client{ accessToken: accessToken }.
const simplePublicObjectInput = {
properties: {
email: contactData.email,
firstname: contactData.firstname,
lastname: contactData.lastname,
phone: contactData.phone || '',
company: contactData.company || '',
// Add any other HubSpot contact properties you want to set
const apiResponse = await hubspotClient.crm.contacts.basicApi.createsimplePublicObjectInput.
console.log'Contact created successfully:', JSON.stringifyapiResponse.body, null, 2.
return apiResponse.body.
} catch e {
console.error'Error creating contact:', e.message.
// You might want to log the full error response for debugging
if e.response && e.response.data {
console.error'HubSpot API Error Details:', JSON.stringifye.response.data, null, 2.
throw new Error'Failed to create HubSpot contact.'.
// Example usage you'd typically call this after receiving form data
const exampleContact = {
email: '[email protected]',
firstname: 'Jane',
lastname: 'Doe',
phone: '555-123-4567',
company: 'Example Corp',
// createHubSpotContactexampleContact
// .thencontact => console.log'Contact creation initiated:', contact.id
// .catcherr => console.error'Failed to process contact:', err.message.
This demonstrates how you can create contacts easily. You could use this in conjunction with a custom form submission: your frontend sends data to your Node.js server, and your server then uses `@hubspot/api-client` to create or update contact records based on that data. This gives you immense power to tailor how form submissions map to your CRM.
Best Practices for Seamless HubSpot Form Integration with NPM
No matter which integration method you choose, a few best practices will help you build robust, secure, and effective HubSpot forms using npm.
# 1. Secure Your API Keys and Tokens
This is paramount. Never expose your HubSpot API keys or private app access tokens directly in client-side code. If you’re using direct API submissions or the `@hubspot/api-client`, always route your requests through a secure backend server. Use environment variables like with `dotenv` in Node.js to store these sensitive credentials.
# 2. Map Form Fields Accurately
When sending data to HubSpot, the `name` attributes of your form fields must exactly match the internal property names in HubSpot for the data to be correctly captured. Double-check these names in your HubSpot account settings to avoid frustrating submission errors.
# 3. Implement Robust Error Handling
Things can go wrong: network issues, incorrect data, API rate limits. Implement comprehensive error handling in both your frontend for user feedback and backend for logging and debugging. HubSpot's API provides clear error messages, so use them to inform your debugging process and user experience.
# 4. Don't Forget Tracking HUTK
For HubSpot to correctly track visitors and associate form submissions with their browsing history, you need to include the `hutk` HubSpot User Tracking Key cookie in your API submission's `context` object. If you're building a custom frontend, you'll need to extract this cookie from the user's browser and send it to your backend with the form data. Libraries often handle this for you, but it's vital for proper analytics.
# 5. Consider GDPR and Consent
If your audience is in regions with strict data privacy regulations like GDPR, make sure your forms include appropriate consent checkboxes. When submitting via API, you can include `legalConsentOptions` in your payload to record user consent within HubSpot.
# 6. Thorough Testing is Key
Before deploying any new form integration, test it rigorously. Submit test data, check your HubSpot CRM to ensure contacts and properties are created/updated correctly, and verify that any associated workflows are triggered. Use HubSpot's form submission debug tools if available.
# 7. Utilize Hidden Fields for Context
Hidden fields are incredibly useful for capturing additional, non-user-entered data, like UTM parameters, referring URLs, or specific campaign IDs. This enriches the data in HubSpot and helps with segmentation and reporting.
# 8. Keep Packages Up-to-Date Carefully
Regularly update your npm packages to benefit from bug fixes, performance improvements, and new features. However, always check the package's changelog for any breaking changes before updating, especially for major version bumps.
Advanced Considerations
As you get more comfortable, you might explore:
* HubSpot Serverless Functions: HubSpot itself offers serverless functions where you can install npm packages and write Node.js code to handle form submissions and other logic directly within your HubSpot portal, reducing the need for an external server. This is currently a beta feature, but it's a powerful option for keeping your logic close to your HubSpot data.
* Webhooks: Beyond form submissions, HubSpot's webhooks can notify your application in real-time about events in HubSpot e.g., new contact created, property updated, allowing for even deeper two-way integration.
Using npm to integrate your HubSpot forms offers a world of possibilities for customization, flexibility, and robust data management. Whether you opt for direct API calls or leverage convenient React packages, you're now equipped to build forms that not only look great but also perform flawlessly within your HubSpot ecosystem.
Frequently Asked Questions
# What is the difference between embedding a HubSpot form directly and using an npm package or API?
Embedding a HubSpot form directly usually involves copying a JavaScript snippet provided by HubSpot into your HTML. This is quick but offers limited styling and functional customization, and can sometimes clash with modern frontend frameworks. Using an npm package provides a wrapper that integrates better with frameworks like React, offering more control over design and behavior, often with simpler setup for common use cases. Directly using the HubSpot Forms API often via `axios` or `fetch` in Node.js gives you the most control, allowing you to build forms from scratch and precisely manage data submission and styling, but it requires more manual coding.
# Can I fully customize the look and feel of a HubSpot form using npm?
Yes, absolutely! This is one of the biggest advantages. When you use the HubSpot Forms API directly, you're essentially building your own HTML form, giving you complete freedom to apply your own CSS and JavaScript. Many React-specific npm packages, like `@ez-digital/react-hubspot-hook-form`, also offer extensive props for styling and customizing the generated form elements to match your application's design.
# Is it safe to put my HubSpot Portal ID and Form GUID in client-side code?
While your Portal ID and Form GUID are generally considered public knowledge they're often visible in embed codes, it's still best practice to handle form submissions through a secure backend server-side when possible, especially if you're sending any sensitive data or using API keys/access tokens. This prevents malicious users from potentially spamming your form endpoint or trying to misuse your HubSpot credentials. Modern React packages often guide you towards this server-side submission for security.
# What is the `hutk` and why is it important for HubSpot form submissions?
The `hutk` HubSpot User Tracking Key is a cookie that HubSpot uses to identify a visitor and track their activity on your website. When you submit a form via the HubSpot Forms API, including the `hutk` in the `context` object of your payload allows HubSpot to associate that form submission with the correct contact record and their historical interactions on your site. Without it, HubSpot might create a new contact record even if the visitor already exists, or miss valuable tracking data.
# Which npm package should I use for HubSpot forms in a React project?
For modern React projects, `@ez-digital/react-hubspot-hook-form` is a strong contender, especially if you want deep customization and client-side validation using `react-hook-form`. `@aaronhayes/react-use-hubspot-form` is another popular choice for simpler hook-based embedding. If you're building with Next.js, `next-hubspot` is specifically optimized for that framework. Always check the package's documentation, community activity, and last update date to ensure it's well-maintained.
# Can I use the `@hubspot/api-client` npm package to submit forms?
The `@hubspot/api-client` package is primarily designed for broader interactions with the HubSpot CRM API e.g., creating contacts, updating deals, fetching data. While you *could* use it to, for example, create a contact after a custom form submission on your server, for direct form submissions, HubSpot provides a specific Forms API endpoint `/submissions/v3/integration/submit`. Many developers find it more direct to use `axios` or `fetch` to hit this specific Forms API endpoint when *only* submitting form data, reserving `@hubspot/api-client` for more comprehensive CRM operations.
# How do I handle file uploads with HubSpot forms via npm?
Handling file uploads through the HubSpot Forms API generally involves a slightly different process. Instead of including the file data directly in the JSON payload, you typically need to upload the file to a separate HubSpot file endpoint first e.g., using the File Upload API if you're using `@hubspot/api-client`, and then pass the file ID or URL back to your form submission as a field value. The specifics can vary, so it's always best to consult HubSpot's official developer documentation for the latest guidance on file uploads.
Understanding HubSpot Notifications: Your Business’s Digital Lifeline
Leave a Reply