Back to docs
API Reference

Research Automation: How to Build Real-Time Research Pipelines with Webhooks

Build automated research pipelines on Koji: event-triggered interviews, a signed webhook when each one is finished and scored, and insight routing to Slack, your CRM or a warehouse.

The 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.


The pipeline at a glance

StageWhat happensKoji surface
1. TriggerA product event starts an interviewPOST /interviews/start
2. CollectThe respondent has the conversationYour UI on the message API, or the embed widget
3. Detect and analyzeKoji scores the interview and pushes an eventinterview.completed webhook, then GET /interviews/{id} for the full analysis
4. RouteInsights flow to where your team worksYour receiver pushes to Slack, CRM, or warehouse

Stage 1: Trigger interviews from product events

Any 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:

// Example: trigger an exit interview when a user cancels
async function onSubscriptionCancelled(user) {
  const res = await fetch('https://www.koji.so/api/v1/interviews/start', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer ' + process.env.KOJI_API_KEY,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      respondent: {
        external_id: user.id,
        display_name: user.firstName,
        metadata: { plan: user.plan, cancelled_at: new Date().toISOString() },
      },
      mode: 'text',
    }),
  })

  const interview = await res.json()

  // Keep session_token too: your UI drives the conversation with it
  return interview
}

The two fields doing the heavy lifting:

  • 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.
  • 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.

Full request reference in Starting Interviews via API.


Stage 2: Collect the conversation

Two ways to run the interview itself:


Stage 3: Receive the webhook and pull the analysis

Set up the push once:

  1. Open the study and go to Integrate, then Webhooks. Only workspace owners and admins can add or change webhooks.
  2. Click Add webhook and paste your receiver's public https:// URL.
  3. Pick interview.completed, and choose Only this study or All studies, including new ones.
  4. Copy the signing secret (it starts with whsec_) into your server's environment as KOJI_WEBHOOK_SECRET.
  5. Click Send test event and check the delivery log for a 2xx.

From 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.

Here is a receiver in Node with Express and the official Standard Webhooks library:

// npm install express standardwebhooks
import express from 'express'
import { Webhook } from 'standardwebhooks'

const app = express()
const wh = new Webhook(process.env.KOJI_WEBHOOK_SECRET)

// Raw body: the signature covers the exact bytes Koji sent.
app.post('/koji/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
  let event
  try {
    event = wh.verify(req.body.toString('utf8'), req.headers)
  } catch {
    return res.status(401).end()
  }

  // Answer fast: any 2xx within 10 seconds counts as delivered.
  res.status(200).end()

  if (event.type !== 'interview.completed') return // e.g. webhook.test
  if (await alreadyProcessed(req.headers['webhook-id'])) return // retries reuse the id

  await queue.add('koji-interview', event.data) // do the real work off the request
})

What the event gives you, and what it doesn't:

  • 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.
  • 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:
// In your queue worker
async function handleCompleted(data) {
  const res = await fetch(data.links.api, {
    headers: { 'Authorization': `Bearer ${process.env.KOJI_API_KEY}` },
  })
  const interview = await res.json()
  await route(data, interview) // stage 4
}

Key behaviors to build around:

  • 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.
  • The event is the trigger, not the payload. Keep the webhook handler tiny, and let a worker do the API read and the routing.
  • 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 when you backfill.

Every field, the signature scheme and the delivery rules are in Webhook Setup.


Stage 4: Route the insights

Once the worker has the event and the full interview, routing is plain integration work. Slack is the classic first target:

// After your worker fetches the full interview
async function route(data, interview) {
  const summary = interview.analysis?.summary ?? 'Analysis pending'

  await fetch(process.env.SLACK_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      text: `${data.study_name}: interview with ${data.participant.external_id ?? 'an anonymous participant'} ` +
        `(${data.trust.quality_level ?? 'not scored'})\n${summary}\n${data.links.app}`,
    }),
  })
}

Other 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.

No-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 for a self-hosted version with signature checks.


Putting it together

The whole interview lifecycle, runnable end to end in Node, for testing the API side of the pipeline:

// Full interview lifecycle: start → message → complete.
// Node 18+ (built-in fetch). Reads your key from the environment.
const API_KEY = process.env.KOJI_API_KEY
const BASE = 'https://www.koji.so/api/v1'
const HEADERS = { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }

async function main() {
  // 1. Start
  const started = await fetch(`${BASE}/interviews/start`, {
    method: 'POST',
    headers: HEADERS,
    body: JSON.stringify({ respondent: { external_id: 'user_8271' }, mode: 'text' }),
  }).then(r => r.json())
  console.log('AI:', started.initial_message)

  const session = { 'X-Session-Token': started.session_token }

  // 2. One message exchange (SSE)
  const res = await fetch(`${BASE}/interviews/${started.interview_id}/message`, {
    method: 'POST',
    headers: { ...HEADERS, ...session },
    body: JSON.stringify({ content: 'I found onboarding confusing.' }),
  })
  let reply = ''
  const reader = res.body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''
  while (true) {
    const { value, done } = await reader.read()
    if (done) break
    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split('\n')
    buffer = lines.pop()
    for (const line of lines) {
      if (!line.startsWith('data: ')) continue
      const frame = JSON.parse(line.slice(6))
      if (frame.type === 'chunk') reply += frame.content
    }
  }
  console.log('AI:', reply)

  // 3. Complete. Once Koji has scored it, your webhook receiver gets
  // interview.completed with external_id user_8271.
  await fetch(`${BASE}/interviews/${started.interview_id}/complete`, {
    method: 'POST',
    headers: { ...HEADERS, ...session },
    body: JSON.stringify({ reason: 'natural' }),
  })
}

main()

In 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).


Polling and the embed event: still useful as backups

Webhooks are the main signal, and the older patterns still have a place:

  • 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.
  • 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.

FAQ

Is this pipeline real-time?

Close 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.

Do I need one pipeline per study?

No. 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.

How do I connect an interview back to the user who triggered it?

Set 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.

What permissions should the pipeline's keys have?

The 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.


Related Resources

Related Articles

Amplitude + Koji: Trigger AI Interviews from Product Analytics and Pipe Insights Back as Events

How to close the loop between Amplitude product analytics and Koji AI interviews — fire interview links to users in specific Amplitude cohorts, and pipe interview themes, sentiment, and quality scores back into Amplitude as user properties and custom events.

API Authentication

How Koji Headless API authentication works: pk_live_ API keys, permissions, session tokens, and origin allowlists.

Automated User Research Platform: From Question to Report Without a Moderator

A practical guide to automated user research platforms. Learn what real research automation looks like in 2026, where rule-based survey tools fall short, and how AI-native platforms close the loop end-to-end.

Exporting Research Data from Koji: CSV, JSON, and Transcript Access

A complete guide to every way you can get your interview data out of Koji — from one-click CSV downloads to automated API pipelines.

Google Sheets + Koji: Launch AI Interviews from a Spreadsheet and Auto-Log Every Insight Back

Turn a Google Sheet of contacts into a batch of Koji AI interviews, and auto-append every completed interview's themes, sentiment, quality score, and transcript link back to a live results tab — no data stack required.

Headless API Overview

Manage interviews programmatically with the Koji REST API — start, message, and complete interviews from your own code.

Sync Koji Customer Interviews to HubSpot: Live Insights on Every Contact

Push Koji interview transcripts, themes, and quality scores onto HubSpot contact and company records using the Koji API and the HubSpot API.

Jira + Koji: Auto-File Customer-Research-Backed Tickets and Close the Loop on Every Fix

Send Koji AI interview themes, customer quotes, and quality scores directly into Jira as fully-formed tickets — and pipe Jira ticket resolution back to the participants who reported it.

Connect Koji to Make (Make.com): Build No-Code Customer Research Automations

Use Make (formerly Integromat) scenarios to trigger Koji AI interviews from any app and route themes, sentiment, and transcripts to Slack, Notion, your CRM, or a spreadsheet, no code, using HTTP modules and Koji webhooks.

Mixpanel + Koji: Trigger AI Interviews from Product Events and Pipe Insights Back as Properties

Trigger Koji AI-moderated interviews from Mixpanel cohorts and behavior, then pipe themes, sentiment, and quality scores back into Mixpanel as events and user profile properties.

Connect Koji to n8n: Build Self-Hosted Customer Research Pipelines

Wire Koji into n8n with signed webhooks to build self-hosted pipelines that route every completed interview into Notion, Linear, Slack, your CRM, or any other system, without sending data through a third-party automation cloud.

Personalized Interview Links: Send Targeted Research Invitations to Every Participant

Give every imported participant a private Koji interview link that skips the lead form, ties their response to them, and lets you track and chase non-responders. Covers CSV import, distribution through your own tools, and tracking.

Product-Led Growth Research: How to Combine Usage Data with Qualitative Interviews

A complete guide for PLG teams on using qualitative AI interviews to answer the why behind activation, retention, and expansion data.

Rate Limits and CORS

Per-key rate limits, X-RateLimit headers, 429 handling with backoff, quota errors, and how CORS works on the Koji API.

Sync Koji AI Interviews to Salesforce: Customer Insights on Every Account, Contact, and Opportunity

Push Koji interview quotes, themes, sentiment and quality scores into Salesforce with a webhook-driven worker, or send personal interview links from a Salesforce report with no code.

Segment + Koji: Trigger AI Interviews from CDP Audiences and Sync Insights Back as Traits

Use Segment Audiences and events to trigger Koji AI-moderated interviews, then pipe summaries, key insights and sentiment back into Segment as track events and user traits that fan out to every downstream tool.

Send Research Insights to Slack: Real-Time Customer Interview Notifications via Webhooks

Get customer interview insights from Koji into Slack. There is no native Slack app, but Koji sends a signed interview.completed webhook from any study (Integrate, then Webhooks), which a small receiver or Zapier, Make or n8n turns into a Slack message seconds after each interview. Step-by-step setup with message recipes.

Structured Questions in AI Interviews

Mix quantitative data collection — scales, ratings, multiple choice, ranking — with AI-powered conversational follow-up in a single interview.

User Research API: Embed AI Interviews into Any Product or Workflow

How to use Koji's User Research API to run AI-moderated interviews from your own backend. Covers REST endpoints, the embed widget, signed completion webhooks, authentication, rate limits, and headless interview patterns.

Webhook Setup

Set up Koji webhooks: get a signed interview.completed message on your server each time a participant finishes, with your own participant ID and a quality score.

Connect Koji to Zapier: Automate Customer Research Workflows in Minutes

Route every completed AI customer interview from Koji into 6,000+ Zapier apps — including Notion, Linear, Salesforce, Airtable, and Gmail. A step-by-step integration guide.

Zendesk + Koji: Trigger AI Interviews from Support Tickets and Sync Insights Back to Every Conversation

Use Zendesk triggers to invite customers to Koji AI-moderated interviews from solved tickets, low CSAT, or specific tags, tie each interview to its ticket through the headless API, and have a small scheduled worker post themes, sentiment, and a response link back onto the ticket.