Skip to content
LogoLogo

How to register an action handler

This guide shows you how to connect an action node in a flow to a function in your application. You need an action in your project first, with a key. See Actions.

A published action that starts a workflow runs without a handler. A handler under its key replaces the workflow.

1. Register the handler

Pass an actions object to createClient(). Each key must match an action key from the dashboard:

import { createClient } from 'picked'
 
const picked = createClient({
  projectId: 'your-project-id',
  actions: {
    'track-signup': () => {
      analytics.track('signup_completed')
    },
    notify: (params) => {
      sendNotification(params)
    },
  },
})

The SDK calls the function that matches when the flow reaches the action node.

2. Throw only for a true error

The flow takes the failure branch when your handler throws or its promise rejects. Throw when the request itself did not complete:

'check-eligibility': async () => {
  const response = await fetch('/api/eligibility')
  // Throw only when the request itself fails. That takes the failure branch.
  if (!response.ok) throw new Error('Eligibility request failed')
}

3. Return a response

The value that your handler returns is the response of the action. Code that runs the action reads this value:

'quote-premium': async ({ responses }) => {
  const age = responses.find((r) => r.fieldKey === 'age')?.value
  const { premium } = await fetch(`/api/premium?age=${age}`).then((r) => r.json())
  return { premium }
}

4. Record a negative answer as a response

A valid negative result is not a failure. An endpoint can answer 200 with a "no". Store that value as a response and branch on it with a condition instead:

'check-serviced-area': async ({ client, responses }) => {
  const postcode = responses.find((r) => r.fieldKey === 'postcode')?.value
  const { serviced } = await fetch(`/api/serviced?postcode=${postcode}`).then((r) => r.json())
  // Store the outcome as a response. A later condition then takes the branch.
  client.responses.register('is-serviced', serviced)
}