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 plane | Data plane | |
|---|---|---|
| Direction | Hive → n8n REST API | Hive → n8n webhook URL |
| Carries | Workflow and credential CRUD | ResponseResponseOne person's set of answers to a Survey. The atomic unit of data HiveCFM analyses. events |
| Auth | X-N8N-API-KEY on every call | Whatever the n8n webhook node checks |
| Code | lib/n8n/client.ts, lib/n8n/service.ts | app/api/(internal)/pipeline/route.ts |
| Set up by | Tenant provisioning, automatically | A 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:
- Get the webhook URL from the deployed n8n workflow (control plane created it; open n8n or call
GET /api/v1/workflows). - Register it as a HiveCFM webhook, in the UI under the environment’s integrations, or via the management API.
- Choose triggers:
responseCreated,responseUpdated,responseFinished. - 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.
- 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
| Header | Always sent | Meaning |
|---|---|---|
content-type: application/json | yes | |
webhook-id | yes | UUIDv7 message id, unique per delivery |
webhook-timestamp | yes | Unix seconds |
webhook-signature | only when the row has a secret | Standard 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.
| Method | n8n endpoint |
|---|---|
createWorkflow / getWorkflow / updateWorkflow / deleteWorkflow | /workflows, /workflows/:id |
activateWorkflow / deactivateWorkflow | PATCH /workflows/:id with { active } |
listWorkflows(tags) | GET /workflows?tags=... |
createCredential / updateCredential / deleteCredential / listCredentials | /credentials, /credentials/:id |
createTag | POST /tags |
getExecution | GET /executions/:id |
healthCheck | GET /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.
- A HiveCFM API key is minted through the
ApiKeymodel, labelledn8n-integration-<organizationId>and scoped to that organization withread: true, write: true, manage: false. - An n8n credential of type
httpHeaderAuthis created carrying that key in thex-api-keyheader. - 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.
| Operation | Effect |
|---|---|
rotateTenantCredentials | Mints a new key, updates the n8n credential in place, deletes the old ApiKey row. Workflows keep working; nothing needs re-deploying |
revokeTenantCredentials | Deletes the n8n credential, clears n8nCredentialId, deletes the ApiKey row |
removeTenantWorkflows | Deactivates and deletes every workflow tagged tenant-<organizationId>, then revokes credentials |
getTenantN8nStatus | Credential 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 template | Webhook path | What it does |
|---|---|---|
response-created-handler | /webhook/<org>/response-created | Fetches response detail back from the management API, then a stub Function node |
low-csat-alert | /webhook/<org>/low-csat-alert | IF on data.kpiScores.csatScore <= 2, then builds an alert object |
contact-sync | /webhook/<org>/contact-sync | Fetches 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:
| Token | Replaced 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
| Variable | Purpose |
|---|---|
N8N_BASE_URL | Where 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_KEY | Sent as X-N8N-API-KEY. Empty string if unset, so calls fail with 401 rather than a clear error |
N8N_WEBHOOK_BASE_URL | Substituted into templates as {{WEBHOOK_BASE_URL}} |
OIDC_N8N_CLIENT_ID / OIDC_N8N_CLIENT_SECRET | n8n 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 andparameterizeWorkflow.hivecfm-core/apps/web/lib/tenant/provisioning.ts— theN8N_CONFIGUREDsaga 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.