Integrationsn8n (Automation)

n8n (Automation)

n8n is the answer to “can HiveCFM integrate with our CRM / ticketing system / chat tool”. Hive does not ship a connector per vendor and is not going to. It emits a well-shaped event, and n8n does the vendor-specific work: transform, branch, authenticate, retry, call the other system.

The practical consequence: any system reachable over HTTP is already integrable, with no change to hivecfm-core. New integrations are workflow edits, not releases.

Two planes, and only one is automatic

Control planeData plane
DirectionHive → n8n REST APIHive → n8n webhook URL
CarriesWorkflow and credential CRUDResponseResponseOne person's set of answers to a Survey. The atomic unit of data HiveCFM analyses. events
AuthX-N8N-API-KEY on every callWhatever the n8n webhook node checks
Codelib/n8n/client.ts, lib/n8n/service.tsapp/api/(internal)/pipeline/route.ts
Set up byTenant provisioning, automaticallyA human, manually

Control plane, built for you at tenant creation:

Data plane, which nobody builds for you:

The two meet at one place only: the webhook URL of a workflow the control plane created has to be pasted into a HiveCFM Webhook row by hand.

Closing the loop, the part provisioning does not do

deployWorkflowTemplates creates n8n workflows whose webhook nodes listen at paths like /webhook/<organizationId>/response-created. Nothing in the codebase creates a matching HiveCFM Webhook row. Provisioning builds the receiver and never connects the sender.

To make events actually flow:

  1. Get the webhook URL from the deployed n8n workflow (control plane created it; open n8n or call GET /api/v1/workflows).
  2. Register it as a HiveCFM webhook, in the UI under the environment’s integrations, or via the management API.
  3. Choose triggers: responseCreated, responseUpdated, responseFinished.
  4. Set a secret on the webhook row unless you have another way to authenticate the caller. Without a secret, Hive sends no signature at all.
  5. Optionally scope it to specific surveyIds. An empty list means every survey in the environment.

This is also the whole story for non-n8n consumers. Anything that can accept an HTTP POST is a first-class integration target through the same webhook row. n8n is the recommended consumer, not a required one.

The payload your workflow receives

Emitted from app/api/(internal)/pipeline/route.ts, once per matching webhook row.

{
  "webhookId": "<id of the Webhook row that matched>",
  "event": "responseFinished",
  "data": {
    "id": "<responseId>",
    "data": { "<questionId>": "<answer>" },
    "meta": {},
    "finished": true,
    "kpiScores": {
      "csatScore": 2,
      "cesScore": null,
      "fcrScore": null,
      "npsScore": null
    },
    "survey": {
      "title": "CSAT - Branch Visit",
      "type": "link",
      "status": "inProgress",
      "createdAt": "...",
      "updatedAt": "..."
    }
  }
}

data is the full Response row spread in, plus two additions: kpiScores and a trimmed survey object.

⚠️

The survey name is at data.survey.title. There is no data.surveyName and no top-level surveyName. Workflows that branch on survey name must read data.survey.title, and some bundled templates get this wrong. See the closed-loop example.

The JSON above is the HTTP body Hive sends. Inside n8n, the Webhook node nests that body one level down, so expressions usually read $json.body.data..., not $json.data.... Check the Webhook node’s output on a real execution before writing the rest of the workflow: the bundled templates assume the un-prefixed root.

kpiScores is read from the Response row when present and computed in memory otherwise, so pre-backfill responses still carry scores. Keys are csatScore, cesScore, fcrScore, npsScore; each is null when the survey has no such question.

Headers and timeout

HeaderAlways sentMeaning
content-type: application/jsonyes
webhook-idyesUUIDv7 message id, unique per delivery
webhook-timestampyesUnix seconds
webhook-signatureonly when the row has a secretStandard Webhooks HMAC over id, timestamp, and body

Delivery is a single attempt with a 5-second timeout and no retry queue. A slow or briefly-down consumer loses the event. If loss matters, have n8n acknowledge fast and queue the real work inside the workflow.

Control-plane API

N8nClient wraps the n8n public REST API at {N8N_BASE_URL}/api/v1.

Methodn8n endpoint
createWorkflow / getWorkflow / updateWorkflow / deleteWorkflow/workflows, /workflows/:id
activateWorkflow / deactivateWorkflowPATCH /workflows/:id with { active }
listWorkflows(tags)GET /workflows?tags=...
createCredential / updateCredential / deleteCredential / listCredentials/credentials, /credentials/:id
createTagPOST /tags
getExecutionGET /executions/:id
healthCheckGET /healthz, 5-second AbortSignal.timeout, returns false rather than throwing

Per-tenant credentials

createTenantCredentials(organizationId) is the useful part of the design: n8n never gets a shared god key.

  1. A HiveCFM API key is minted through the ApiKey model, labelled n8n-integration-<organizationId> and scoped to that organization with read: true, write: true, manage: false.
  2. An n8n credential of type httpHeaderAuth is created carrying that key in the x-api-key header.
  3. The credential id is stored on Organization.n8nCredentialId.

Workflows therefore call back into Hive as a real, revocable, org-scoped API key, and cannot administer the organization.

OperationEffect
rotateTenantCredentialsMints a new key, updates the n8n credential in place, deletes the old ApiKey row. Workflows keep working; nothing needs re-deploying
revokeTenantCredentialsDeletes the n8n credential, clears n8nCredentialId, deletes the ApiKey row
removeTenantWorkflowsDeactivates and deletes every workflow tagged tenant-<organizationId>, then revokes credentials
getTenantN8nStatusCredential id, API key metadata including lastUsedAt, workflow list, live reachability
⚠️

Tenant workflow lifecycle is keyed entirely off the n8n tag tenant-<organizationId>. Untag a workflow in the n8n UI and Hive loses its handle: it will not appear in status, and teardown will not remove it. The tag is the only join.

Templates and parameterization

deployWorkflowTemplates prefers rows in the WorkflowTemplate table where isDefault = true, and falls back to the three templates hardcoded in lib/n8n/templates.ts.

Bundled templateWebhook pathWhat it does
response-created-handler/webhook/<org>/response-createdFetches response detail back from the management API, then a stub Function node
low-csat-alert/webhook/<org>/low-csat-alertIF on data.kpiScores.csatScore <= 2, then builds an alert object
contact-sync/webhook/<org>/contact-syncFetches contacts from the management API

They are starting points, not finished integrations: two of the three end in a Function node that returns a shaped object and calls nothing.

Parameterization is four token substitutions performed on the serialized template JSON:

TokenReplaced with
{{ORGANIZATION_ID}}the organization id
{{WEBHOOK_BASE_URL}}N8N_WEBHOOK_BASE_URL
{{HIVECFM_URL}}WEBAPP_URL
{{CREDENTIAL_ID}}Organization.n8nCredentialId, or empty string
⚠️

parameterizeWorkflow does JSON.stringify, four global string replaces, then JSON.parse. It is blind to JSON structure. Any value that happens to contain a token string is rewritten too, and a substituted value containing a quote or backslash produces invalid JSON and a parse error at deploy time. Keep template tokens out of free-text fields.

Environment variables

VariablePurpose
N8N_BASE_URLWhere Hive reaches the n8n REST API and /healthz. Container-internal in the composeDocker ComposeThe YAML file and CLI that spin up Postgres, Redis, MinIO, MailHog locally with one command. stack
N8N_API_KEYSent as X-N8N-API-KEY. Empty string if unset, so calls fail with 401 rather than a clear error
N8N_WEBHOOK_BASE_URLSubstituted into templates as {{WEBHOOK_BASE_URL}}
OIDC_N8N_CLIENT_ID / OIDC_N8N_CLIENT_SECRETn8n signing in against Hive’s OIDC provider, separate from the API-key path above
🚫

Do not rely on the defaults. N8N_WEBHOOK_BASE_URL falls back to one host in lib/n8n/templates.ts and a different host in docker-compose.yml, and N8N_BASE_URL falls back to the container name in lib/n8n/client.ts but to a localhost port in lib/oidc/clients.ts. Deployed templates silently point at whichever host won. Set all of these explicitly per environment.

Where to look in the code

  • hivecfm-core/apps/web/lib/n8n/client.ts — N8nClient, every control-plane call.
  • hivecfm-core/apps/web/lib/n8n/service.ts — deploy, credential lifecycle, teardown, status.
  • hivecfm-core/apps/web/lib/n8n/templates.ts — the three bundled templates and parameterizeWorkflow.
  • hivecfm-core/apps/web/lib/tenant/provisioning.ts — the N8N_CONFIGURED saga step and its compensation.
  • hivecfm-core/apps/web/app/api/(internal)/pipeline/route.ts — webhook selection, payload assembly, signature, 5-second timeout.
  • hivecfm-core/apps/web/app/lib/pipelines.ts — sendToPipeline, the internal call that starts a dispatch.
  • hivecfm-core/scripts/n8n-workflow.json — the closed-loop router covered in the example.

HiveCFM Developer Hub — internal team guide