n8n Automation

n8n CRM Automation: HubSpot & Salesforce Patterns

Petru Constantin
••11 min read
#n8n#crm#hubspot#salesforce#automation#lead-management#workflow

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the n8n 2.47.7 (stable), HubSpot CRM API v3 and the Salesforce REST API documentation.

n8n CRM Automation: HubSpot and Salesforce Integration Patterns

CRM automation is essential for scaling sales operations and maintaining data consistency across systems. This guide covers comprehensive n8n workflow patterns for HubSpot and Salesforce integration, including lead management, contact synchronization, and deal tracking.

CRM Integration Architecture

Multi-CRM Sync Strategy

// Code node (Run Once for All Items): map HubSpot contacts to Salesforce Lead fields.
// Authentication lives on the n8n HubSpot and Salesforce credentials, not in code.
// Fields ending in __c are custom fields you create in Salesforce first.
// Lead Status values are picklist values of your Salesforce org: replace the examples.
 
const LEAD_SOURCE = {
  ORGANIC_SEARCH: 'Web',
  PAID_SEARCH: 'Paid Search',
  SOCIAL_MEDIA: 'Social Media',
  EMAIL_MARKETING: 'Email',
  REFERRALS: 'Referral',
  DIRECT_TRAFFIC: 'Web',
  OTHER_CAMPAIGNS: 'Other'
};
 
const LIFECYCLE_TO_STATUS = {
  subscriber: 'Open - Not Contacted',
  lead: 'Open - Not Contacted',
  marketingqualifiedlead: 'Working - Contacted',
  salesqualifiedlead: 'Working - Contacted',
  opportunity: 'Working - Contacted',
  customer: 'Closed - Converted',
  evangelist: 'Closed - Converted'
};
 
const STATUS_TO_LIFECYCLE = {
  'Open - Not Contacted': 'lead',
  'Working - Contacted': 'marketingqualifiedlead',
  'Closed - Converted': 'customer',
  'Closed - Not Converted': 'other'
};
 
// HubSpot property values can arrive as plain values or as { value } objects
const read = (props, name) => props?.[name]?.value ?? props?.[name];
 
function determineSyncDirection(hubspotRecord, salesforceRecord, strategy = 'newest_wins') {
  if (!salesforceRecord) return 'hubspot_to_salesforce';
  if (!hubspotRecord) return 'salesforce_to_hubspot';
 
  const hubspotModified = new Date(read(hubspotRecord.properties, 'hs_lastmodifieddate'));
  const salesforceModified = new Date(salesforceRecord.LastModifiedDate);
 
  switch (strategy) {
    case 'newest_wins':
      return hubspotModified > salesforceModified ? 'hubspot_to_salesforce' : 'salesforce_to_hubspot';
    case 'hubspot_primary':
      return 'hubspot_to_salesforce';
    case 'salesforce_primary':
      return 'salesforce_to_hubspot';
    default:
      throw new Error(`Unknown conflict strategy: ${strategy}`);
  }
}
 
function buildDescription(props) {
  const parts = [];
  if (read(props, 'hs_analytics_first_url')) parts.push(`First page: ${read(props, 'hs_analytics_first_url')}`);
  if (read(props, 'hs_analytics_num_page_views')) parts.push(`Page views: ${read(props, 'hs_analytics_num_page_views')}`);
  if (read(props, 'recent_conversion_event_name')) parts.push(`Last conversion: ${read(props, 'recent_conversion_event_name')}`);
  return parts.join('\n');
}
 
function mapHubSpotToSalesforce(contact) {
  const p = contact.properties;
  return {
    FirstName: read(p, 'firstname') || '',
    LastName: read(p, 'lastname') || 'Unknown',
    Email: read(p, 'email'),
    Phone: read(p, 'phone'),
    Company: read(p, 'company') || 'Unknown',
    Title: read(p, 'jobtitle'),
    Website: read(p, 'website'),
    Street: read(p, 'address'),
    City: read(p, 'city'),
    State: read(p, 'state'),
    PostalCode: read(p, 'zip'),
    Country: read(p, 'country'),
    LeadSource: LEAD_SOURCE[read(p, 'hs_analytics_source')] || 'Other',
    Status: LIFECYCLE_TO_STATUS[read(p, 'lifecyclestage')] || 'Open - Not Contacted',
    Description: buildDescription(p),
    HubSpot_Contact_ID__c: String(contact.id ?? contact.vid ?? ''),
    Lead_Score__c: parseInt(read(p, 'hubspotscore'), 10) || 0
  };
}
 
function mapSalesforceToHubSpot(record) {
  return {
    properties: {
      firstname: record.FirstName,
      lastname: record.LastName,
      email: record.Email,
      phone: record.Phone,
      company: record.Company,
      jobtitle: record.Title,
      website: record.Website,
      address: record.Street,
      city: record.City,
      state: record.State,
      zip: record.PostalCode,
      country: record.Country,
      salesforce_lead_id: record.Id,          // custom HubSpot property
      salesforce_lead_status: record.Status,  // custom HubSpot property
      lifecyclestage: STATUS_TO_LIFECYCLE[record.Status] || 'lead'
    }
  };
}
 
// Input: HubSpot contacts. Use mapSalesforceToHubSpot the same way for the reverse direction.
return $input.all().map(item => ({
  json: {
    hubspotId: item.json.id ?? item.json.vid,
    salesforceLead: mapHubSpotToSalesforce(item.json)
  }
}));

Lead Management Workflows

New Lead Processing

The lead pipeline uses these nodes, in this order:

  1. HubSpot Trigger with the events Contact Created and Contact Property Changed (property lifecyclestage).
  2. HubSpot node, Contact → Get a contact, with the contact ID from the trigger output.
  3. Code node "Enrich Lead Data" (below), in Run Once for Each Item mode.
  4. Switch node in Rules mode on {{ $json.enrichment.tier }}: A to output 0, B to output 1, everything else to the fallback output.
  5. On each branch, an Edit Fields (Set) node that adds the queue, priority and SLA (enterprise_sales / 4 h, sales_development / 24 h, marketing_nurture / 72 h).
  6. Salesforce node, Lead → Create, mapping Last Name and Company (falling back to the email domain when Company is empty) and the custom fields you created (HubSpot_Contact_ID__c, Lead_Quality_Score__c, Lead_Tier__c).
  7. HubSpot node, Contact → Create/Update a contact, matching on the email, to write the new Salesforce ID back to a custom salesforce_lead_id property.
  8. On the A branch only, a Slack node (Message → Send) to #sales-hot-leads.

The original example was a workflow JSON with Function nodes, Switch and Merge parameters from older node versions and no typeVersion; rebuild it in the editor from these steps instead of importing it.

// Code node "Enrich Lead Data", mode: Run Once for Each Item (return one object)
const contact = $input.item.json;
const props = contact.properties ?? {};
const read = (name) => props[name]?.value ?? props[name];
 
const email = read('email');
const domain = email ? String(email).split('@')[1]?.toLowerCase() : null;
 
let qualityScore = 0;
 
// Company email rather than a personal mailbox
const freeEmailDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com'];
if (domain && !freeEmailDomains.includes(domain)) qualityScore += 30;
 
if (read('phone')) qualityScore += 20;
if (read('company')) qualityScore += 15;
if (read('jobtitle')) qualityScore += 15;
 
// HubSpot score contribution, capped at 20
const hsScore = parseInt(read('hubspotscore'), 10) || 0;
qualityScore += Math.min(hsScore / 5, 20);
 
return {
  json: {
    ...contact,
    enrichment: {
      domain,
      qualityScore,
      tier: qualityScore >= 70 ? 'A' : qualityScore >= 50 ? 'B' : qualityScore >= 30 ? 'C' : 'D',
      needsEnrichment: !read('company') || !read('jobtitle')
    }
  }
};

Deal/Opportunity Sync

// Code node (Run Once for All Items): map HubSpot deals to Salesforce Opportunity fields
// and pick follow-up actions by stage. The stage IDs below are examples: check your
// HubSpot pipeline stage IDs and your Salesforce StageName picklist before using them.
// The previous stage isn't a deal property; take it from the Deal Property Changed
// trigger event or from the deal's property history.
 
const HUBSPOT_TO_SALESFORCE_STAGE = {
  appointmentscheduled: 'Qualification',
  qualifiedtobuy: 'Needs Analysis',
  presentationscheduled: 'Proposal/Price Quote',
  decisionmakerboughtin: 'Negotiation/Review',
  contractsent: 'Negotiation/Review',
  closedwon: 'Closed Won',
  closedlost: 'Closed Lost'
};
 
const PROBABILITY = {
  appointmentscheduled: 20,
  qualifiedtobuy: 40,
  presentationscheduled: 60,
  decisionmakerboughtin: 80,
  contractsent: 90,
  closedwon: 100,
  closedlost: 0
};
 
const STAGE_ACTIONS = {
  closedwon: ['create_customer_record', 'notify_success_team', 'trigger_onboarding'],
  closedlost: ['record_loss_reason', 'add_to_win_back_campaign'],
  contractsent: ['create_contract_task', 'notify_legal']
};
 
const isoDate = (d) => new Date(d).toISOString().split('T')[0];
 
return $input.all().map(item => {
  const deal = item.json;
  const read = (name) => deal.properties?.[name]?.value ?? deal.properties?.[name];
  const stage = read('dealstage');
 
  const opportunity = {
    Name: read('dealname'),
    Amount: parseFloat(read('amount')) || 0,
    CloseDate: read('closedate') ? isoDate(read('closedate')) : isoDate(Date.now() + 30 * 24 * 60 * 60 * 1000),
    StageName: HUBSPOT_TO_SALESFORCE_STAGE[stage] || 'Qualification',
    Description: read('description'),
    Probability: PROBABILITY[stage] ?? 10,
    Type: 'New Business',
    HubSpot_Deal_ID__c: String(deal.id ?? deal.dealId ?? '') // custom field
  };
 
  return {
    json: {
      dealId: deal.id ?? deal.dealId,
      currentStage: stage,
      opportunity,
      actions: STAGE_ACTIONS[stage] || [],
      timestamp: new Date().toISOString()
    }
  };
});

Bi-Directional Contact Sync

The scheduled two-way sync, rebuilt from current node operations:

  1. Schedule Trigger every 15 minutes.
  2. HubSpot node, Contact → Get recently created/updated contacts.
  3. Salesforce node, Contact → Get many records, filtered on LastModifiedDate since the last run. Keep the last run time in workflow static data from a Code node, rather than assuming exactly 15 minutes have passed.
  4. Two Code nodes that turn each side into the same shape (source, email, lastModified, data) and skip records whose last change came from the other system's sync, which stops echo loops.
  5. Merge node in Append mode.
  6. Code node that deduplicates by lowercased email and keeps the newest change.
  7. Switch node on {{ $json.source }}.
  8. HubSpot changes: Salesforce node, Contact → Upsert. Upsert matches on an External ID field; standard Email isn't one, so create a custom external ID field (for example HubSpot_Contact_ID__c) and match on that.
  9. Salesforce changes: HubSpot node, Contact → Create/Update a contact, which matches on email.
  10. After each write, update the sync markers on the other side (salesforce_sync_date and salesforce_sync_direction in HubSpot, HubSpot_Sync_Date__c and HubSpot_Sync_Direction__c in Salesforce); step 4 reads them.

Activity and Task Sync

// Code node (Run Once for All Items): map tasks between Salesforce and HubSpot CRM v3 tasks
// (HubSpot endpoint: POST /crm/v3/objects/tasks). Salesforce Status, Priority and Type
// are org picklists: adjust the values to yours.
// Associations need IDs from the target CRM: look up the HubSpot contact for the
// Salesforce WhoId (for example through HubSpot_Contact_ID__c) before creating the task.
 
function salesforceTaskToHubSpot(task) {
  return {
    properties: {
      hs_timestamp: new Date(task.ActivityDate ?? Date.now()).toISOString(), // required: due date
      hs_task_subject: task.Subject,
      hs_task_body: task.Description ?? '',
      hs_task_status: task.Status === 'Completed' ? 'COMPLETED' : 'NOT_STARTED',
      hs_task_priority: task.Priority === 'High' ? 'HIGH' : task.Priority === 'Low' ? 'LOW' : 'MEDIUM',
      hs_task_type: task.Type === 'Call' ? 'CALL' : task.Type === 'Email' ? 'EMAIL' : 'TODO'
    }
  };
}
 
function hubspotTaskToSalesforce(task) {
  const p = task.properties ?? {};
  return {
    Subject: p.hs_task_subject || 'HubSpot task',
    Description: p.hs_task_body || '',
    Status: p.hs_task_status === 'COMPLETED' ? 'Completed' : 'Not Started',
    Priority: p.hs_task_priority === 'HIGH' ? 'High' : p.hs_task_priority === 'LOW' ? 'Low' : 'Normal',
    ActivityDate: p.hs_timestamp ? new Date(p.hs_timestamp).toISOString().split('T')[0] : null,
    HubSpot_Task_ID__c: String(task.id) // custom field
  };
}
 
// Salesforce REST records carry attributes.type; HubSpot v3 objects carry properties
return $input.all().map(item => ({
  json: item.json.attributes?.type === 'Task'
    ? { target: 'hubspot', sourceId: item.json.Id, record: salesforceTaskToHubSpot(item.json) }
    : { target: 'salesforce', sourceId: item.json.id, record: hubspotTaskToSalesforce(item.json) }
}));

Data Quality and Deduplication

// Code node (Run Once for All Items): find and merge duplicate contacts.
// Input: one item per contact with email, firstname, lastname, company, phone,
// jobtitle, id and lastModified. Pairwise comparison is O(n^2): run it on batches.
 
class CRMDeduplicator {
  constructor(options = {}) {
    this.matchThreshold = options.matchThreshold || 0.85;
  }
 
  findDuplicates(contacts) {
    const duplicateGroups = [];
    const processed = new Set();
 
    for (let i = 0; i < contacts.length; i++) {
      if (processed.has(i)) continue;
 
      const contact = contacts[i];
      const group = [contact];
 
      for (let j = i + 1; j < contacts.length; j++) {
        if (processed.has(j)) continue;
 
        const candidate = contacts[j];
        const score = this.calculateMatchScore(contact, candidate);
 
        if (score >= this.matchThreshold) {
          group.push({ ...candidate, matchScore: score });
          processed.add(j);
        }
      }
 
      if (group.length > 1) {
        processed.add(i);
        duplicateGroups.push(group);
      }
    }
 
    return duplicateGroups;
  }
 
  calculateMatchScore(contact1, contact2) {
    let score = 0;
    let weights = 0;
 
    // Email match (highest weight)
    if (contact1.email && contact2.email) {
      weights += 40;
      if (contact1.email.toLowerCase() === contact2.email.toLowerCase()) {
        score += 40;
      }
    }
 
    // Name match
    const name1 = `${contact1.firstname || ''} ${contact1.lastname || ''}`.toLowerCase().trim();
    const name2 = `${contact2.firstname || ''} ${contact2.lastname || ''}`.toLowerCase().trim();
 
    if (name1 && name2) {
      weights += 30;
      score += this.stringSimilarity(name1, name2) * 30;
    }
 
    // Company match
    if (contact1.company && contact2.company) {
      weights += 15;
      score += this.stringSimilarity(
        contact1.company.toLowerCase(),
        contact2.company.toLowerCase()
      ) * 15;
    }
 
    // Phone match
    const phone1 = this.normalizePhone(contact1.phone);
    const phone2 = this.normalizePhone(contact2.phone);
 
    if (phone1 && phone2) {
      weights += 15;
      if (phone1 === phone2) {
        score += 15;
      }
    }
 
    return weights > 0 ? score / weights : 0;
  }
 
  // String similarity from the Levenshtein distance
  stringSimilarity(str1, str2) {
    if (!str1 || !str2) return 0;
    if (str1 === str2) return 1;
 
    const len1 = str1.length;
    const len2 = str2.length;
 
    const matrix = Array(len1 + 1).fill(null)
      .map(() => Array(len2 + 1).fill(null));
 
    for (let i = 0; i <= len1; i++) matrix[i][0] = i;
    for (let j = 0; j <= len2; j++) matrix[0][j] = j;
 
    for (let i = 1; i <= len1; i++) {
      for (let j = 1; j <= len2; j++) {
        const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
        matrix[i][j] = Math.min(
          matrix[i - 1][j] + 1,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j - 1] + cost
        );
      }
    }
 
    return 1 - matrix[len1][len2] / Math.max(len1, len2);
  }
 
  normalizePhone(phone) {
    if (!phone) return null;
    return String(phone).replace(/\D/g, '').slice(-10);
  }
 
  // Newest record wins; empty fields are filled from the older records
  mergeContacts(duplicates) {
    if (duplicates.length === 0) return null;
    if (duplicates.length === 1) return duplicates[0];
 
    const sorted = [...duplicates].sort((a, b) =>
      new Date(b.lastModified || 0) - new Date(a.lastModified || 0)
    );
 
    const { matchScore, ...primary } = sorted[0];
    const mergedFrom = [];
 
    for (let i = 1; i < sorted.length; i++) {
      const { matchScore: _score, ...record } = sorted[i];
      mergedFrom.push(record.id);
 
      for (const [key, value] of Object.entries(record)) {
        if (!primary[key] && value) {
          primary[key] = value;
        }
      }
    }
 
    primary.mergedFrom = mergedFrom;
    primary.mergedAt = new Date().toISOString();
 
    return primary;
  }
}
 
const dedup = new CRMDeduplicator({ matchThreshold: 0.85 });
const contacts = $input.all().map(item => item.json);
 
// One item per duplicate group: review or write the merged record back to the CRM
return dedup.findDuplicates(contacts).map(group => ({
  json: {
    duplicateIds: group.map(c => c.id),
    merged: dedup.mergeContacts(group)
  }
}));

Conclusion

CRM automation with n8n keeps HubSpot and Salesforce in step when every sync records where a change came from, so the next run doesn't send it back. Key patterns covered include:

  1. Lead processing pipelines with quality scoring and intelligent routing
  2. Bi-directional sync handling conflicts and maintaining data consistency
  3. Deal/Opportunity sync with stage mapping between systems
  4. Activity synchronization keeping engagement history unified
  5. Data quality management with deduplication and validation

These patterns ensure sales teams have accurate, up-to-date information regardless of which CRM they use.


Official references

Related on this site: AI Automation: Zapier vs Make vs n8n - Which One to Choose?, n8n Customer Onboarding: End-to-End Automation, Customer Support Automation with n8n. More articles in the n8n Automation category.

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.