DEV Community

memories2digital
memories2digital

Posted on • Originally published at memories2digital.com.au

3 2

Automatically creating contacts & deals in Hubspot using Netlify Functions

Here at Memories 2 Digital, we deploy our website as a static site to Netlify. This makes the website super fast & means we don't need to maintain servers. While this is awesome, we don't have a traditional back end to automate stuff like interactions with our CRM (HubSpot).

Using the Hubspot API with Netlify Functions.

Luckily for us, Netlify provides a quick way to add serverless functions to your static site code. There's a couple of steps required to make this work.

First off, we need to add our Hubspot API key in the Netlify build settings. You'll find the in your site's settings under "Build and Deploy"

Add the variable your environment variables (these can be used in your function)

Add the variable your environment variables (these can be used in your function)

First, we need to create a netlify.toml (if you don't already have one) with the following content (to instruct netlify where your functions live)

[build]
functions = "./functions"

Next, jump into your prefered code editor and create a new folder in the root of your project called functions, and inside this create a deal folder. Finally, create a deal.js file in the folder (where you'll write your code).

Here's the code for the function. I've commented the important parts, but it's pretty simple.

exports.handler = async (event, context) => {
  try {
    if (event.httpMethod !== 'POST') {
      // Block GET requests
      return { statusCode: 400, body: null }
    }

    const Hubspot = require('hubspot')
    // This will use your build enviroment varible
    const hubspot = new Hubspot({ apiKey: process.env.HUBSPOT_KEY })

    const body = JSON.parse(event.body)

    // Create the contact for the deal. This will update the existing one if it already exists

    const properties = [
      { 'property': 'firstname', 'value': body.firstName },
      { 'property': 'lastname', 'value': body.lastName },
      { 'property': 'phone', 'value': body.phone },
    ]

    const contact = await hubspot.contacts.createOrUpdate(body.form.email, { properties })

    const deal = await hubspot.deals.create({
      // Use the contact ID from the previous call
      associations: { associatedVids: [contact.vid] },
      properties: [
        {
          'value': `Website Order for ${body.firstName} ${body.lastName}`,
          'name': 'dealname',
        },
        {
          // You'll want to grab from your deal stage config in Hubspot (click the code symbol to find this number)
          'value': 2413030,
          'name': 'dealstage',
        },
        {
          'value': 'default',
          'name': 'pipeline',
        },
        {
          // This is a float, for example 10.50
          'value': body.estimate,
          'name': 'amount',
        },
        {
          // Add any other fields you want
          'value': body.whatever,
          'name': 'whatever',
        },
      ],
    })

    // Return a 200 if it succeeds
    return { statusCode: 200, body: JSON.stringify({ success: true }) }

  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}

Push your code up & netlify will deploy your functions. You can test them in an API tool like Postman using the following URL:

http://your.domain/.netlify/functions/order

You can now wire it up on the frontend, using javascript or a plain form to submit the data directly to your serverless function!

You're now running dynamic code on your static site!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay