hubspot-reference-architecture

Implement a production-ready HubSpot integration architecture with layered design. Use when designing new HubSpot integrations, reviewing project structure, or establishing architecture standards for HubSpot CRM applications. Trigger with phrases like "hubspot architecture", "hubspot project structure", "hubspot integration design", "hubspot best practices layout", "hubspot layers".

1,868 stars

Best use case

hubspot-reference-architecture is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Implement a production-ready HubSpot integration architecture with layered design. Use when designing new HubSpot integrations, reviewing project structure, or establishing architecture standards for HubSpot CRM applications. Trigger with phrases like "hubspot architecture", "hubspot project structure", "hubspot integration design", "hubspot best practices layout", "hubspot layers".

Teams using hubspot-reference-architecture should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/hubspot-reference-architecture/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/hubspot-pack/skills/hubspot-reference-architecture/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/hubspot-reference-architecture/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How hubspot-reference-architecture Compares

Feature / Agenthubspot-reference-architectureStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Implement a production-ready HubSpot integration architecture with layered design. Use when designing new HubSpot integrations, reviewing project structure, or establishing architecture standards for HubSpot CRM applications. Trigger with phrases like "hubspot architecture", "hubspot project structure", "hubspot integration design", "hubspot best practices layout", "hubspot layers".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# HubSpot Reference Architecture

## Overview

Production-ready layered architecture for HubSpot CRM integrations with typed clients, service abstraction, caching, and webhook handling.

## Prerequisites

- TypeScript 5+ project
- `@hubspot/api-client` v13+ installed
- Understanding of layered architecture patterns

## Instructions

### Step 1: Project Structure

```
my-hubspot-integration/
├── src/
│   ├── hubspot/                    # HubSpot infrastructure layer
│   │   ├── client.ts              # Singleton @hubspot/api-client wrapper
│   │   ├── types.ts               # HubSpot-specific types
│   │   ├── errors.ts              # Error classification
│   │   ├── cache.ts               # Response caching
│   │   └── associations.ts        # Association type constants
│   ├── services/                   # Business logic layer
│   │   ├── contact.service.ts     # Contact CRUD + business rules
│   │   ├── deal.service.ts        # Deal pipeline operations
│   │   ├── company.service.ts     # Company management
│   │   └── sync.service.ts        # Data synchronization
│   ├── api/                        # API layer
│   │   ├── routes/
│   │   │   ├── contacts.ts        # REST endpoints
│   │   │   ├── deals.ts
│   │   │   └── webhooks.ts        # Webhook receiver
│   │   └── middleware/
│   │       ├── auth.ts            # Request auth
│   │       └── webhook-verify.ts  # HubSpot signature verification
│   ├── jobs/                       # Background jobs
│   │   ├── sync-contacts.ts       # Scheduled sync
│   │   └── process-webhooks.ts    # Async event processing
│   └── index.ts
├── tests/
│   ├── unit/
│   │   ├── services/
│   │   └── mocks/hubspot.ts       # Shared mock factory
│   └── integration/
│       └── hubspot.integration.test.ts
├── config/
│   ├── default.ts                 # Shared config
│   └── production.ts              # Production overrides
└── package.json
```

### Step 2: Infrastructure Layer

```typescript
// src/hubspot/client.ts
import * as hubspot from '@hubspot/api-client';

let instance: hubspot.Client | null = null;

export function getHubSpotClient(): hubspot.Client {
  if (!instance) {
    instance = new hubspot.Client({
      accessToken: process.env.HUBSPOT_ACCESS_TOKEN!,
      numberOfApiCallRetries: 3,
    });
  }
  return instance;
}

// src/hubspot/associations.ts
// Default association type IDs (HUBSPOT_DEFINED category)
export const ASSOCIATION_TYPES = {
  CONTACT_TO_COMPANY: 1,
  CONTACT_TO_DEAL: 3,
  COMPANY_TO_DEAL: 5,
  CONTACT_TO_TICKET: 16,
  NOTE_TO_CONTACT: 202,
  TASK_TO_CONTACT: 204,
  NOTE_TO_DEAL: 214,
} as const;

// src/hubspot/errors.ts
export class HubSpotError extends Error {
  constructor(
    message: string,
    public readonly statusCode: number,
    public readonly category: string,
    public readonly correlationId: string,
    public readonly retryable: boolean
  ) {
    super(message);
    this.name = 'HubSpotError';
  }
}

export function wrapError(error: any): HubSpotError {
  const status = error?.code || error?.statusCode || 500;
  const body = error?.body || {};
  return new HubSpotError(
    body.message || error.message,
    status,
    body.category || 'UNKNOWN',
    body.correlationId || '',
    [429, 500, 502, 503, 504].includes(status)
  );
}
```

### Step 3: Service Layer

```typescript
// src/services/contact.service.ts
import type { SimplePublicObject } from '@hubspot/api-client/lib/codegen/crm/contacts';
import { getHubSpotClient } from '../hubspot/client';
import { ASSOCIATION_TYPES } from '../hubspot/associations';
import { wrapError } from '../hubspot/errors';

const CONTACT_PROPS = ['firstname', 'lastname', 'email', 'phone', 'lifecyclestage', 'company'];

export class ContactService {
  private client = getHubSpotClient();

  async findByEmail(email: string): Promise<SimplePublicObject | null> {
    try {
      const result = await this.client.crm.contacts.searchApi.doSearch({
        filterGroups: [{
          filters: [{ propertyName: 'email', operator: 'EQ', value: email }],
        }],
        properties: CONTACT_PROPS,
        limit: 1, after: 0, sorts: [],
      });
      return result.results[0] || null;
    } catch (error) {
      throw wrapError(error);
    }
  }

  async upsert(email: string, properties: Record<string, string>): Promise<SimplePublicObject> {
    const existing = await this.findByEmail(email);
    if (existing) {
      return this.client.crm.contacts.basicApi.update(existing.id, { properties });
    }
    return this.client.crm.contacts.basicApi.create({
      properties: { email, ...properties },
      associations: [],
    });
  }

  async associateWithCompany(contactId: string, companyId: string): Promise<void> {
    await this.client.crm.associations.v4.basicApi.create(
      'contacts', contactId, 'companies', companyId,
      [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: ASSOCIATION_TYPES.CONTACT_TO_COMPANY }]
    );
  }
}

// src/services/deal.service.ts
export class DealService {
  private client = getHubSpotClient();
  private pipelineCache: any[] | null = null;

  async getPipelines() {
    if (!this.pipelineCache) {
      const result = await this.client.crm.pipelines.pipelinesApi.getAll('deals');
      this.pipelineCache = result.results;
    }
    return this.pipelineCache;
  }

  async createInPipeline(
    dealName: string,
    amount: number,
    pipelineName: string,
    stageName: string,
    associations: { contactId?: string; companyId?: string }
  ) {
    const pipelines = await this.getPipelines();
    const pipeline = pipelines.find(p => p.label === pipelineName) || pipelines[0];
    const stage = pipeline.stages.find((s: any) => s.label === stageName) || pipeline.stages[0];

    const assocArray = [];
    if (associations.contactId) {
      assocArray.push({
        to: { id: associations.contactId },
        types: [{ associationCategory: 'HUBSPOT_DEFINED' as const, associationTypeId: 3 }],
      });
    }
    if (associations.companyId) {
      assocArray.push({
        to: { id: associations.companyId },
        types: [{ associationCategory: 'HUBSPOT_DEFINED' as const, associationTypeId: 5 }],
      });
    }

    return this.client.crm.deals.basicApi.create({
      properties: {
        dealname: dealName,
        amount: String(amount),
        pipeline: pipeline.id,
        dealstage: stage.id,
      },
      associations: assocArray,
    });
  }
}
```

### Step 4: Data Flow

```
User Request → API Routes → Service Layer → HubSpot Client → HubSpot API
                                 ↕                   ↕
                            Business Rules      Response Cache
                                 ↕
                            Background Jobs → Webhook Events
```

### Step 5: Configuration

```typescript
// config/default.ts
export const config = {
  hubspot: {
    retries: 3,
    cache: {
      contactTtlMs: 5 * 60 * 1000,     // 5 minutes
      pipelineTtlMs: 60 * 60 * 1000,   // 1 hour
      propertyTtlMs: 60 * 60 * 1000,   // 1 hour
    },
    batch: {
      maxSize: 100,
      concurrency: 5,
    },
  },
};

// config/production.ts
export const productionConfig = {
  hubspot: {
    retries: 5,
    cache: {
      contactTtlMs: 2 * 60 * 1000,     // shorter in prod
    },
  },
};
```

## Output

- Layered architecture separating infrastructure, services, and API
- Typed client with error classification
- Association type constants (no magic numbers)
- Service classes with business logic encapsulation
- Configurable caching and retry policies

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| Circular dependencies | Wrong layering | Services import hubspot/, never the reverse |
| Type errors | Missing SDK type imports | Import from `@hubspot/api-client/lib/codegen/crm/` |
| Test isolation | Shared client state | Use `resetHubSpotClient()` in test teardown |
| Cache invalidation | Stale data | Invalidate on webhook events |

## Resources

- [@hubspot/api-client GitHub](https://github.com/HubSpot/hubspot-api-nodejs)
- [CRM Objects Guide](https://developers.hubspot.com/docs/guides/api/crm/understanding-the-crm)
- [Associations v4 API](https://developers.hubspot.com/docs/guides/api/crm/associations)

## Next Steps

For multi-environment setup, see `hubspot-multi-env-setup`.

Related Skills

workhuman-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman reference architecture for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman reference architecture".

wispr-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow reference architecture for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr reference architecture".

windsurf-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Implement Windsurf reference architecture with optimal project structure and AI configuration. Use when designing workspace configuration for Windsurf, setting up team standards, or establishing architecture patterns that maximize Cascade effectiveness. Trigger with phrases like "windsurf architecture", "windsurf project structure", "windsurf best practices", "windsurf team setup", "optimize for cascade".

windsurf-architecture-variants

1868
from jeremylongshore/claude-code-plugins-plus-skills

Choose workspace architectures for different project scales in Windsurf. Use when deciding how to structure Windsurf workspaces for monorepos, multi-service setups, or polyglot codebases. Trigger with phrases like "windsurf workspace strategy", "windsurf monorepo", "windsurf project layout", "windsurf multi-service", "windsurf workspace size".

webflow-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Implement Webflow reference architecture — layered project structure, client wrapper, CMS sync service, webhook handlers, and caching layer for production integrations. Trigger with phrases like "webflow architecture", "webflow project structure", "how to organize webflow", "webflow integration design", "webflow best practices".

vercel-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Implement a Vercel reference architecture with layered project structure and best practices. Use when designing new Vercel projects, reviewing project structure, or establishing architecture standards for Vercel applications. Trigger with phrases like "vercel architecture", "vercel project structure", "vercel best practices layout", "how to organize vercel project".

vercel-architecture-variants

1868
from jeremylongshore/claude-code-plugins-plus-skills

Choose and implement Vercel architecture blueprints for different scales and use cases. Use when designing new Vercel projects, choosing between static, serverless, and edge architectures, or planning how to structure a multi-project Vercel deployment. Trigger with phrases like "vercel architecture", "vercel blueprint", "how to structure vercel", "vercel monorepo", "vercel multi-project".

veeva-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault reference architecture for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva reference architecture".

vastai-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Implement Vast.ai reference architecture for GPU compute workflows. Use when designing ML training pipelines, structuring GPU orchestration, or establishing architecture patterns for Vast.ai applications. Trigger with phrases like "vastai architecture", "vastai design pattern", "vastai project structure", "vastai ml pipeline".

twinmind-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Production architecture for meeting AI systems using TwinMind: transcription pipeline, memory vault, action item workflow, and calendar integration. Use when implementing reference architecture, or managing TwinMind meeting AI operations. Trigger with phrases like "twinmind reference architecture", "twinmind reference architecture".

together-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

Together AI reference architecture for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together reference architecture".

techsmith-reference-architecture

1868
from jeremylongshore/claude-code-plugins-plus-skills

TechSmith reference architecture for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith reference architecture".