{"site":{"name":"Koji","description":"AI-native customer research platform that helps teams conduct, analyze, and synthesize customer interviews at scale.","url":"https://www.koji.so","contentTypes":["blog","documentation"],"lastUpdated":"2026-12-05T00:58:18.608Z"},"content":[{"type":"documentation","id":"d795de05-22fb-4a0c-a666-eae3de9d075b","slug":"research-automation-webhooks","title":"Research Automation: How to Build Real-Time Research Pipelines with Webhooks","url":"https://www.koji.so/docs/research-automation-webhooks","summary":"Architecture guide for automated research pipelines on Koji: trigger interviews from product events like signup or churn with the Headless API, run them in your own UI or the embed widget, receive a signed interview.completed webhook when each interview is finished and scored, fetch the transcript and analysis from the read endpoint, and route insights to Slack, a CRM or a warehouse. Webhooks are set up per study under Integrate, then Webhooks, on the Insights, Interviews and Enterprise plans. They are retried for about 35 hours and logged with resend. API keys come with the Interviews and Enterprise plans.","content":"# Research Automation: How to Build Real-Time Research Pipelines with Webhooks\n\nThe dream pipeline is simple: a user churns, an interview starts automatically, the AI digs into why, and the insight lands in Slack before your standup. You can build that on Koji today. A product event starts the interview through the Headless API, and when the participant finishes, Koji pushes a signed `interview.completed` webhook to your server, so there is nothing to poll. Add the webhook in any study under **Integrate → Webhooks**. Webhooks are included on the Insights, Interviews and Enterprise plans, and the API keys used to start and read interviews come with the Interviews and Enterprise plans.\n\n---\n\n## The pipeline at a glance\n\n| Stage | What happens | Koji surface |\n|---|---|---|\n| 1. Trigger | A product event starts an interview | `POST /interviews/start` |\n| 2. Collect | The respondent has the conversation | Your UI on the message API, or the embed widget |\n| 3. Detect and analyze | Koji scores the interview and pushes an event | `interview.completed` webhook, then `GET /interviews/{id}` for the full analysis |\n| 4. Route | Insights flow to where your team works | Your receiver pushes to Slack, CRM, or warehouse |\n\n---\n\n## Stage 1: Trigger interviews from product events\n\nAny event in your system can start an interview: a cancellation, a signup, a support ticket closing, an NPS detractor score. A one-study key needs no study id (send `study_id` with a key for several studies), and the `respondent` object carries your CRM linkage:\n\n```javascript\n// Example: trigger an exit interview when a user cancels\nasync function onSubscriptionCancelled(user) {\n  const res = await fetch('https://www.koji.so/api/v1/interviews/start', {\n    method: 'POST',\n    headers: {\n      'Authorization': 'Bearer ' + process.env.KOJI_API_KEY,\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify({\n      respondent: {\n        external_id: user.id,\n        display_name: user.firstName,\n        metadata: { plan: user.plan, cancelled_at: new Date().toISOString() },\n      },\n      mode: 'text',\n    }),\n  })\n\n  const interview = await res.json()\n\n  // Keep session_token too: your UI drives the conversation with it\n  return interview\n}\n```\n\nThe two fields doing the heavy lifting:\n\n- `external_id` ties the interview to your user record. It comes back in the webhook as `data.participant.external_id` and in the read response, so the pipeline can join results to the right account without storing anything at start time.\n- `metadata` is free-form JSON stored on the respondent. Stamp it with the trigger context (plan, cohort, event timestamp) so analysis lands with its context attached.\n\nFull request reference in [Starting Interviews via API](/docs/starting-interviews-via-api).\n\n---\n\n## Stage 2: Collect the conversation\n\nTwo ways to run the interview itself:\n\n- **Your own UI on the message API.** Your client drives the conversation with the `session_token`, streaming AI replies over SSE. See [Sending Messages via API](/docs/sending-messages-via-api) and [Completing Interviews via API](/docs/completing-interviews-via-api).\n- **The embed widget.** Drop the iframe into your app or a follow-up page and let it run the whole conversation. See [Embed Widget Reference](/docs/embed-widget-reference).\n\n---\n\n## Stage 3: Receive the webhook and pull the analysis\n\nSet up the push once:\n\n1. Open the study and go to **Integrate**, then **Webhooks**. Only workspace owners and admins can add or change webhooks.\n2. Click **Add webhook** and paste your receiver's public `https://` URL.\n3. Pick `interview.completed`, and choose **Only this study** or **All studies, including new ones**.\n4. Copy the signing secret (it starts with `whsec_`) into your server's environment as `KOJI_WEBHOOK_SECRET`.\n5. Click **Send test event** and check the delivery log for a 2xx.\n\nFrom then on, Koji POSTs an event each time a participant finishes and the interview has been scored, including interviews a researcher closes with \"Mark as done\". Partial and abandoned interviews, previews and deleted interviews are not sent.\n\nHere is a receiver in Node with Express and the official Standard Webhooks library:\n\n```javascript\n// npm install express standardwebhooks\nimport express from 'express'\nimport { Webhook } from 'standardwebhooks'\n\nconst app = express()\nconst wh = new Webhook(process.env.KOJI_WEBHOOK_SECRET)\n\n// Raw body: the signature covers the exact bytes Koji sent.\napp.post('/koji/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {\n  let event\n  try {\n    event = wh.verify(req.body.toString('utf8'), req.headers)\n  } catch {\n    return res.status(401).end()\n  }\n\n  // Answer fast: any 2xx within 10 seconds counts as delivered.\n  res.status(200).end()\n\n  if (event.type !== 'interview.completed') return // e.g. webhook.test\n  if (await alreadyProcessed(req.headers['webhook-id'])) return // retries reuse the id\n\n  await queue.add('koji-interview', event.data) // do the real work off the request\n})\n```\n\nWhat the event gives you, and what it doesn't:\n\n- **In the event:** `data.interview_id`, `data.study_id` and `study_name`, timing and mode, the participant's `external_id` and `source`, and a `trust` block with `quality_score` (1 to 5), `quality_level` (Shallow, Fair, Good or Excellent), `meets_quality_bar` and `fraud_risk`.\n- **Not in the event:** the transcript and analysis. Your worker fetches those from the URL in `data.links.api` with an API key for that study:\n\n```javascript\n// In your queue worker\nasync function handleCompleted(data) {\n  const res = await fetch(data.links.api, {\n    headers: { 'Authorization': `Bearer ${process.env.KOJI_API_KEY}` },\n  })\n  const interview = await res.json()\n  await route(data, interview) // stage 4\n}\n```\n\nKey behaviors to build around:\n\n- **At least once, in no fixed order.** Failed deliveries are retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours and 24 hours, and anyone can resend one from the delivery log. Every repeat carries the same `webhook-id`, so store the ones you've handled. For anything that pays or writes once, also make `data.interview_id` unique.\n- **The event is the trigger, not the payload.** Keep the webhook handler tiny, and let a worker do the API read and the routing.\n- **The read endpoint authenticates with the API key alone** (`interview:read` permission, no session token), so the worker needs exactly one server-side key per study. Mind the limits in [Rate Limits and CORS](/docs/rate-limits-and-cors) when you backfill.\n\nEvery field, the signature scheme and the delivery rules are in [Webhook Setup](/docs/webhook-setup).\n\n---\n\n## Stage 4: Route the insights\n\nOnce the worker has the event and the full interview, routing is plain integration work. Slack is the classic first target:\n\n```javascript\n// After your worker fetches the full interview\nasync function route(data, interview) {\n  const summary = interview.analysis?.summary ?? 'Analysis pending'\n\n  await fetch(process.env.SLACK_WEBHOOK_URL, {\n    method: 'POST',\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify({\n      text: `${data.study_name}: interview with ${data.participant.external_id ?? 'an anonymous participant'} ` +\n        `(${data.trust.quality_level ?? 'not scored'})\\n${summary}\\n${data.links.app}`,\n    }),\n  })\n}\n```\n\nOther destinations follow the same shape: upsert into your warehouse keyed on `data.interview_id` and `external_id`, attach the summary to the CRM record that triggered the interview, or open a ticket when `meets_quality_bar` is false so someone reviews the interview guide. `data.trust.quality_score` makes a natural first filter: route Good and Excellent interviews to the team channel, and Shallow ones to research ops.\n\nNo-code tools work too. Paste a Zapier, Make or n8n catch-hook URL as the webhook endpoint and filter on `type` = `interview.completed` in the first step. See [n8n Research Automation](/docs/n8n-research-automation) for a self-hosted version with signature checks.\n\n---\n\n## Putting it together\n\nThe whole interview lifecycle, runnable end to end in Node, for testing the API side of the pipeline:\n\n```javascript\n// Full interview lifecycle: start → message → complete.\n// Node 18+ (built-in fetch). Reads your key from the environment.\nconst API_KEY = process.env.KOJI_API_KEY\nconst BASE = 'https://www.koji.so/api/v1'\nconst HEADERS = { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }\n\nasync function main() {\n  // 1. Start\n  const started = await fetch(`${BASE}/interviews/start`, {\n    method: 'POST',\n    headers: HEADERS,\n    body: JSON.stringify({ respondent: { external_id: 'user_8271' }, mode: 'text' }),\n  }).then(r => r.json())\n  console.log('AI:', started.initial_message)\n\n  const session = { 'X-Session-Token': started.session_token }\n\n  // 2. One message exchange (SSE)\n  const res = await fetch(`${BASE}/interviews/${started.interview_id}/message`, {\n    method: 'POST',\n    headers: { ...HEADERS, ...session },\n    body: JSON.stringify({ content: 'I found onboarding confusing.' }),\n  })\n  let reply = ''\n  const reader = res.body.getReader()\n  const decoder = new TextDecoder()\n  let buffer = ''\n  while (true) {\n    const { value, done } = await reader.read()\n    if (done) break\n    buffer += decoder.decode(value, { stream: true })\n    const lines = buffer.split('\\n')\n    buffer = lines.pop()\n    for (const line of lines) {\n      if (!line.startsWith('data: ')) continue\n      const frame = JSON.parse(line.slice(6))\n      if (frame.type === 'chunk') reply += frame.content\n    }\n  }\n  console.log('AI:', reply)\n\n  // 3. Complete. Once Koji has scored it, your webhook receiver gets\n  // interview.completed with external_id user_8271.\n  await fetch(`${BASE}/interviews/${started.interview_id}/complete`, {\n    method: 'POST',\n    headers: { ...HEADERS, ...session },\n    body: JSON.stringify({ reason: 'natural' }),\n  })\n}\n\nmain()\n```\n\nIn production the stages split across your event handlers (stage 1), your UI or the embed (stage 2), and one webhook receiver plus a queue worker (stages 3 and 4).\n\n---\n\n## Polling and the embed event: still useful as backups\n\nWebhooks are the main signal, and the older patterns still have a place:\n\n- **A nightly safety net.** `GET /interviews/{id}` returns status, transcript and analysis. A daily job over the interviews you expected catches anything your receiver missed, for example if it was down longer than the roughly 35-hour retry window. If an endpoint keeps failing for 3 days, Koji turns it off and emails the workspace owners and admins.\n- **The embed event, for the page.** If interviews run in the embed widget, the `koji:interview_completed` browser event fires the moment the participant finishes. Use it for a thank-you state in your app. It only fires in an open tab, so keep the webhook as your source of truth.\n\n---\n\n## FAQ\n\n### Is this pipeline real-time?\n\nClose to it. The webhook fires as soon as the participant finishes and Koji has scored the interview, so your receiver usually hears about it within a minute or two of the last answer.\n\n### Do I need one pipeline per study?\n\nNo. One webhook can cover every study in the workspace (\"All studies, including new ones\"), and `data.study_id` tells them apart. One API key can too: create it for all studies in the workspace, and the worker fetches every transcript with that single `interview:read` key.\n\n### How do I connect an interview back to the user who triggered it?\n\nSet `respondent.external_id` at start time. It comes back as `data.participant.external_id` in the webhook and as `respondent.external_id` in the read response, ready to join against your user table.\n\n### What permissions should the pipeline's keys have?\n\nThe trigger path needs `interview:start`. The worker needs `interview:read`. If your own UI drives conversations, that client-side key needs `interview:chat` and `interview:complete` too. The webhook itself needs no key: you verify it with the signing secret. See [API Key Permissions](/docs/api-permissions).\n\n---\n\n## Related Resources\n\n- [Webhook Setup](/docs/webhook-setup): payload fields, signatures, retries and the delivery log\n- [n8n Research Automation](/docs/n8n-research-automation): a self-hosted, no-code version of this pipeline\n- [Starting Interviews via API](/docs/starting-interviews-via-api): the trigger endpoint in full\n- [Completing Interviews via API](/docs/completing-interviews-via-api): closing interviews from your own UI\n- [Understanding Quality Scores](/docs/understanding-quality-scores): what the score and level in each event mean\n- [Structured Questions Guide](/docs/structured-questions-guide): question types whose answers you can route on","category":"API Reference","lastModified":"2026-12-02T21:57:23.535077+00:00","metaTitle":"Real-Time Research Pipelines | Koji Headless API","metaDescription":"Build an automated research pipeline with Koji: trigger interviews from product events, receive a signed webhook when each finishes, pull the analysis and route insights.","keywords":["research automation webhooks","user research webhook","automated research pipeline","real-time research data","research webhook integration","continuous research automation","qualitative data webhook"],"aiSummary":"Architecture guide for automated research pipelines on Koji: trigger interviews from product events like signup or churn with the Headless API, run them in your own UI or the embed widget, receive a signed interview.completed webhook when each interview is finished and scored, fetch the transcript and analysis from the read endpoint, and route insights to Slack, a CRM or a warehouse. Webhooks are set up per study under Integrate, then Webhooks, on the Insights, Interviews and Enterprise plans. They are retried for about 35 hours and logged with resend. API keys come with the Interviews and Enterprise plans.","aiPrerequisites":["Familiarity with HTTP and REST APIs","Koji workspace on the Interviews or Enterprise plan for API keys (webhooks alone also work on Insights)","A public HTTPS endpoint, or a Zapier, Make or n8n catch hook"],"aiLearningOutcomes":["Design a four-stage research pipeline: trigger, collect, analyze, route","Start interviews automatically from product events with external_id linkage","Receive and verify the interview.completed webhook","Fetch the full analysis and route it into Slack or a data warehouse","Handle retries and repeats with webhook-id and interview_id"],"aiDifficulty":"advanced","aiEstimatedTime":"12 min"}],"pagination":{"total":1,"returned":1,"offset":0}}