> For the complete documentation index, see [llms.txt](https://developer.relaypro.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.relaypro.com/integrations/mitti-safetyculture-alerts.md).

# Mitti (SafetyCulture) Alerts

## Overview

[Mitti](https://mitti.com/) (formerly SafetyCulture) is a frontline operations platform used for inspections, issue reporting, and corrective actions. When a food safety problem is reported as an **Issue** in Mitti, you want the right people to hear about it immediately, wherever they are standing.

Mitti's [webhooks](https://developer.mitti.com/reference/webhooks) send an HTTP POST to a URL you choose whenever an event happens in your organization, including when an Issue is created. This page connects that event to the [Relay Alerts API](https://developer.relaypro.com/docs/relay-alerts-api): a food safety Issue is created in Mitti, a small receiver you host checks it, and every device in the target Workflow Group speaks the message until someone taps the talk button to accept the job.

This page builds a complete, working **food safety alert**.

```mermaid
flowchart LR
    A["Mitti<br/>Issue created<br/>category: Food safety"] --> B["Mitti webhook<br/>POST to your URL"]
    B --> C["Receiver<br/>verify signature<br/>fetch issue<br/>filter + de-duplicate"]
    C --> D["Relay Alerts API<br/>POST /alerts"]
    D --> E["Relay devices<br/>in Workflow Group"]
    E --> F["Acknowledged"]
```

### Why Alerts and not Broadcasts

Relay offers two notification types. Use **Alerts** for food safety. An alert repeats every 30 seconds until a human acknowledges it, and it records who accepted the job, which is the accountability a food safety response needs. A [broadcast](https://developer.relaypro.com/docs/relay-broadcasts-api) plays once with no acknowledgement. That is fine for shift announcements, but wrong for a cooler failure.

### Why a receiver sits in the middle

Unlike many integrations, Mitti cannot call Relay directly. A Mitti webhook registration takes only a list of events and a destination URL. It cannot add a custom `Authorization` header or reshape the body, and Relay requires both. Mitti's payloads are also deliberately small, so details such as the issue title, category, and site must be fetched from the Mitti API.

The receiver in this guide is a small piece of JavaScript with a thin adapter for **Azure Functions**, **AWS Lambda**, or **Cloudflare Workers**. It does four jobs:

1. **Verifies** that the request really came from Mitti, using the HMAC signature Mitti attaches to every webhook.
2. **Fetches the issue** from the Mitti API and checks that it is a food safety issue.
3. **De-duplicates**, because Mitti retries failed deliveries and may deliver the same event more than once.
4. **Calls Relay** with a message written for text-to-speech.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td>Relay</td><td>An <strong>enterprise plan</strong> account. API keys are not available on lower tiers.</td></tr><tr><td>Relay</td><td>A <strong>Workflow Group</strong> containing the users who should receive food safety calls.</td></tr><tr><td>Relay</td><td>Your <strong>subscriber ID</strong> and an <strong>API key</strong>.</td></tr><tr><td>Mitti</td><td>A <strong>Premium or Enterprise plan</strong>. API tokens are not available on lower plans.</td></tr><tr><td>Mitti</td><td>An Issue <strong>category</strong> used for food safety (this guide uses <code>Food safety</code>). Categories are configured in your Mitti organization.</td></tr><tr><td>Mitti</td><td>An API token whose owner can receive webhooks. For a <strong>service user</strong> token, that means the <strong>Override permissions: Manage all data</strong> permission. For a <strong>user</strong> token, the user needs the <strong>Administrator</strong> permission. See Step 4.</td></tr><tr><td>Hosting</td><td>A place to run the receiver at a public <strong>HTTPS URL</strong>: an Azure Function App, an AWS Lambda function with a Function URL, or a Cloudflare Worker. Any other host that can run Node.js 20+ also works.</td></tr></tbody></table>

***

{% stepper %}
{% step %}

## Create the Relay Workflow Group

In [Relay Dash](https://dash.relaypro.com/), open **Incidents** in the left-hand navigation.

Select **Workflow Groups**, then **Create Workflow Group**.

Name the group. This guide uses `food-safety`.

Set the type to **No Type**.

Select the new group, choose **Edit Membership**, and add the users who should be called.

The group name is what the receiver will send in the `groups` array of the API payload.
{% endstep %}

{% step %}

## Collect your Relay credentials

| Value           | Where to find it                                                                              |
| --------------- | --------------------------------------------------------------------------------------------- |
| `subscriber_id` | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details**, listed under **Subscriber** |
| `apikey`        | Relay Dash → **Help** → [**API Keys**](https://dash.relaypro.com/api-keys) → create a key     |

{% hint style="warning" %}
Create a **dedicated API key for this integration** rather than reusing one. If the receiver's hosting account is ever compromised, you want to revoke one key without breaking every other integration you run.
{% endhint %}
{% endstep %}

{% step %}

## Prove the Relay side works

Fire the alert by hand first:

```sh
export subscriber_id=your_subscriber_id
export apikey=your_api_key

curl -X POST \
  -H "Authorization: RelayApiKey $apikey" \
  -H "Content-Type: application/json" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" \
  -d '{"notification": "Test alert from Mitti integration", "groups": ["food-safety"]}' \
  -i
```

A successful call returns `HTTP/2 200` and a task ID:

```json
{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

Devices in `food-safety` should now be speaking the message every 30 seconds. Tap the talk button on one to acknowledge, or cancel it from the terminal:

```sh
curl -X DELETE \
  -H "Authorization: RelayApiKey $apikey" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD"
```

{% hint style="success" %}
If this curl works and the Mitti integration does not, the problem is in the Mitti side or the receiver, not in Relay.
{% endhint %}
{% endstep %}

{% step %}

## Create a Mitti API token

The receiver uses a Mitti API token to read issues. You also use a token to register the webhook in Step 7. Mitti supports two kinds; for a shared, long-running integration, use a **service user** token.

1. Log in to the [Mitti web app](https://app.mitti.com/).
2. Click your organization name in the lower-left corner and select **Integrations**.
3. Select the **API tokens** tab, then **+ Create API token**.
4. Name the token (for example `Relay food safety alerts`) and choose an inactivity expiry (31, 45, 60, or 180 days).
5. Select the permission sets for the service user. Make sure **Override permissions: Manage all data** is included. Mitti requires this permission for a service user to receive webhook payloads, and it also lets the receiver read any issue.
6. Select **Create token**, then copy the token and store it securely before closing the window. It is not shown again.

{% hint style="info" %}
Creating a service user token requires the **Platform management: Organization**, **Permissions**, and **Users** permissions and a full seat. If you would rather use a **user** token, the user must have the **Administrator** permission, and user tokens expire after 30 days of inactivity.

Tokens also expire after a period of inactivity. Because the receiver calls the Mitti API every time an issue is created, a quiet organization could see a token lapse. Choose the longest inactivity window that fits your policy, and set a reminder to rotate it.
{% endhint %}

Set it aside as `MITTI_API_TOKEN`. For more detail see Mitti's [Authentication](https://developer.mitti.com/reference/authentication) guide.
{% endstep %}

{% step %}

## Get the webhook signature secret

Mitti signs every webhook so your receiver can confirm it is genuine. Fetch your organization's signature secret:

```sh
export MITTI_API_TOKEN=your_mitti_token

curl -H "Authorization: Bearer $MITTI_API_TOKEN" \
  "https://api.mitti.com/webhooks/v1/token"
```

The response contains the secret in a `token` field:

```json
{"token":"your-signature-secret"}
```

Set this aside as `MITTI_WEBHOOK_SECRET`.

{% hint style="warning" %}
Treat the signature secret like a password. Anyone who has it can send your receiver forged events that trigger real alerts on Relay devices. If it is exposed, regenerate it with Mitti's [Regenerate signature secret](https://developer.mitti.com/reference/webhooksservice_generatetoken) endpoint and update the receiver.
{% endhint %}
{% endstep %}

{% step %}

## Deploy the receiver

The receiver has two parts: a **platform-neutral core** (`receiver.js`) that holds all of the logic, and a **small adapter** for the platform you host on. The core requires Node.js 20 or later, because it uses the built-in `fetch`, `Request`, `Response`, and Web Crypto APIs.

### The core: `receiver.js`

Use this file unchanged on every platform.

```javascript
// receiver.js
// Mitti (formerly SafetyCulture) "Issue created" webhook -> Relay alert.
//
// Platform-neutral core. It takes a standard Request-like object (method, headers.get,
// text()) and an `env` object of settings, and returns a standard Response. A thin adapter
// for your platform (Azure Functions, AWS Lambda, or Cloudflare Workers) calls handle().
// Requires a runtime with global fetch, Request/Response, and Web Crypto (Node.js 20+,
// Cloudflare Workers).
//
// Settings (passed in `env`):
//   MITTI_WEBHOOK_SECRET    Signature secret from GET https://api.mitti.com/webhooks/v1/token
//   MITTI_API_TOKEN         Mitti API token (service user recommended)
//   RELAY_SUBSCRIBER_ID     Relay subscriber ID
//   RELAY_API_KEY           Relay API key
//   RELAY_GROUP             Relay Workflow Group name (default: food-safety)
//   FOOD_SAFETY_CATEGORIES  Comma-separated Mitti issue categories that should page
//                           (default: "Food safety")
// Optional:
//   SEEN                    A store with get(key) / put(key, value, { expirationTtl }) used to
//                           de-duplicate Mitti retries. Falls back to in-memory, which only
//                           protects a single warm instance.

const MITTI_API = 'https://api.mitti.com';
const RELAY_API = 'https://api.relaypro.com';
const DEDUPE_TTL_SECONDS = 24 * 60 * 60;

const memorySeen = new Map(); // fallback store: key -> expiry (ms)

async function handle(request, env, deps = {}) {
  const fetchFn = deps.fetch || fetch;

  if (request.method !== 'POST') return reply(405, 'Method not allowed');

  // 1. Verify the signature over the RAW body. Do not parse before verifying.
  const raw = await request.text();
  const signature = request.headers.get('x-safetyculture-signature') || '';
  if (!(await validSignature(env.MITTI_WEBHOOK_SECRET, raw, signature))) {
    return reply(401, 'Invalid signature');
  }

  let body;
  try {
    body = JSON.parse(raw);
  } catch {
    return reply(400, 'Invalid JSON');
  }

  // 2. Only act on "Issue created".
  const eventTypes = body?.event?.event_types || [];
  if (!eventTypes.includes('TRIGGER_EVENT_INCIDENT_CREATED')) {
    return reply(200, 'Ignored: not an issue-created event');
  }
  const issueId = body?.resource?.id;
  if (!issueId) return reply(200, 'Ignored: no resource id');

  // 3. De-duplicate. Mitti retries failed deliveries and may deliver duplicates.
  const dedupeKey = `mitti-issue:${issueId}`;
  if (await alreadySeen(env, dedupeKey)) return reply(200, 'Duplicate: already alerted');

  // 4. The webhook payload is small, so fetch the issue to filter and build the message.
  const issueRes = await fetchFn(
    `${MITTI_API}/tasks/v1/incident/${encodeURIComponent(issueId)}`,
    { headers: { Authorization: `Bearer ${env.MITTI_API_TOKEN}` } },
  );
  if (!issueRes.ok) {
    console.error(`Mitti get issue failed: HTTP ${issueRes.status} for ${issueId}`);
    return reply(502, 'Could not fetch issue'); // non-2xx makes Mitti retry
  }
  const issue = (await issueRes.json())?.incident || {};

  const wanted = (env.FOOD_SAFETY_CATEGORIES || 'Food safety')
    .split(',')
    .map((c) => c.trim().toLowerCase())
    .filter(Boolean);
  const category = (issue.category?.key || '').trim().toLowerCase();
  if (!wanted.includes(category)) {
    return reply(200, `Ignored: category "${issue.category?.key || ''}" is not a food safety category`);
  }

  // 5. Build a message that reads well when spoken.
  const title = speakable(issue.task?.title) || 'No description';
  const site = speakable(issue.task?.site?.name);
  const where = site ? ` at ${site}` : '';

  const payload = {
    notification: `Food safety alert${where}. ${title}. Please respond.`,
    groups: [env.RELAY_GROUP || 'food-safety'],
    quorum: 1,
    timeout: 600,
    name: 'mitti-food-safety',
    on_ack: `Accepted. You are responding to the food safety alert${where}.`,
    on_quorum: 'Another team member has taken this call.',
    on_timeout: `Food safety alert${where} was not acknowledged.`,
  };

  // 6. Call Relay.
  const relayRes = await fetchFn(
    `${RELAY_API}/subscribers/${env.RELAY_SUBSCRIBER_ID}/api/v1/alerts`,
    {
      method: 'POST',
      headers: {
        Authorization: `RelayApiKey ${env.RELAY_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    },
  );
  if (relayRes.status !== 200) {
    console.error(`Relay alert failed for issue ${issueId}: HTTP ${relayRes.status} ${await relayRes.text()}`);
    return reply(502, 'Relay alert failed'); // not marked seen, so Mitti's retry can try again
  }
  const taskId = (await relayRes.json())?.task_id;
  await markSeen(env, dedupeKey, taskId || '1');
  console.log(`Relay alert sent for issue ${issueId}, task_id=${taskId}`);
  return reply(200, 'Alert sent', { task_id: taskId });
}

// --- helpers ---------------------------------------------------------------

function reply(status, message, extra = {}) {
  return new Response(JSON.stringify({ message, ...extra }), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

// Keep only characters that speak cleanly; collapse whitespace; cap the length.
function speakable(value) {
  return String(value || '')
    .replace(/[^A-Za-z0-9 .,'-]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, 120);
}

async function validSignature(secret, rawBody, headerValue) {
  if (!secret || !headerValue) return false;
  const key = await crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign'],
  );
  const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawBody));
  const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join('');
  return timingSafeEqual(expected, headerValue.trim().toLowerCase());
}

function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

async function alreadySeen(env, key) {
  if (env.SEEN) return (await env.SEEN.get(key)) != null;
  const expiry = memorySeen.get(key);
  if (expiry && expiry > Date.now()) return true;
  memorySeen.delete(key);
  return false;
}

async function markSeen(env, key, value) {
  if (env.SEEN) return env.SEEN.put(key, value, { expirationTtl: DEDUPE_TTL_SECONDS });
  memorySeen.set(key, Date.now() + DEDUPE_TTL_SECONDS * 1000);
}

module.exports = { handle };
```

### Settings

Every platform uses the same settings. Set them in the platform's configuration, not in source code.

| Setting                  | Purpose                                                                                                                        |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `MITTI_WEBHOOK_SECRET`   | Signature secret from Step 5. Requests that do not match it are rejected.                                                      |
| `MITTI_API_TOKEN`        | Mitti API token from Step 4.                                                                                                   |
| `RELAY_SUBSCRIBER_ID`    | Subscriber ID from Step 2.                                                                                                     |
| `RELAY_API_KEY`          | Relay API key from Step 2.                                                                                                     |
| `RELAY_GROUP`            | Workflow Group to alert. Defaults to `food-safety`.                                                                            |
| `FOOD_SAFETY_CATEGORIES` | Comma-separated list of Mitti Issue categories that should trigger an alert. Matching ignores case. Defaults to `Food safety`. |

{% hint style="warning" %}
`MITTI_WEBHOOK_SECRET`, `MITTI_API_TOKEN`, and `RELAY_API_KEY` are credentials. Keep them in your platform's secret store (Azure Key Vault, AWS Secrets Manager, or Cloudflare secrets) and never commit them to source control.
{% endhint %}

### The adapter for your platform

Mitti may deliver the same event more than once, and the receiver sends only one alert per issue. To do that across restarts and multiple instances, it needs a small persistent store. Each adapter below wires up the natural choice for its platform. Without a store the receiver falls back to memory, which protects only a single running instance and is not suitable for production.

{% tabs %}
{% tab title="Azure Functions" %}
This adapter uses the Node.js **v4 programming model** and stores de-duplication records in **Azure Table Storage**.

Create a Function App that runs a supported Node.js version on Linux (see Microsoft's [Node.js developer reference](https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node) for supported versions and project setup). Lay the project out like this:

```
host.json
package.json
src/
  receiver.js          <- the core, from above
  functions/
    mitti.js           <- the adapter, below
```

`host.json`:

```json
{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}
```

`package.json`:

```json
{
  "name": "mitti-relay-food-safety",
  "version": "1.0.0",
  "private": true,
  "main": "src/functions/*.js",
  "dependencies": {
    "@azure/data-tables": "^13.3.2",
    "@azure/functions": "^4.0.0"
  }
}
```

`src/functions/mitti.js`:

```javascript
// src/functions/mitti.js
// Azure Functions (Node.js, v4 programming model) adapter for the Mitti -> Relay receiver.
const { app } = require('@azure/functions');
const { TableClient } = require('@azure/data-tables');
const { handle } = require('../receiver');

// De-duplication store: Azure Table Storage. By default this uses the Function App's own
// storage account (AzureWebJobsStorage). Set SEEN_STORAGE_CONNECTION to use another account.
const connection = process.env.SEEN_STORAGE_CONNECTION || process.env.AzureWebJobsStorage;
const seen = connection
  ? tableStore(TableClient.fromConnectionString(connection, 'mittiseen', { allowInsecureConnection: connection.includes('127.0.0.1') }))
  : undefined;
if (!seen) console.warn('No storage connection string found; de-duplication is in-memory only.');

app.http('mitti', {
  methods: ['POST'],
  authLevel: 'anonymous', // requests are authenticated by Mitti's HMAC signature
  handler: async (request) => {
    // Azure's HttpRequest already exposes method, headers.get(), and text().
    const res = await handle(request, { ...process.env, SEEN: seen });
    return {
      status: res.status,
      headers: { 'Content-Type': 'application/json' },
      body: await res.text(),
    };
  },
});

function tableStore(client) {
  let ready;
  const ensureTable = () => (ready ||= client.createTable());
  const rowKey = (key) => key.replace(/[^A-Za-z0-9_-]/g, '_');
  return {
    async get(key) {
      await ensureTable();
      try {
        const entity = await client.getEntity('seen', rowKey(key));
        return Number(entity.expires) > Date.now() ? String(entity.value) : null; // expired rows count as unseen
      } catch (err) {
        if (err.statusCode === 404) return null;
        throw err;
      }
    },
    async put(key, value, { expirationTtl }) {
      await ensureTable();
      await client.upsertEntity(
        { partitionKey: 'seen', rowKey: rowKey(key), value: String(value), expires: Date.now() + expirationTtl * 1000 },
        'Replace',
      );
    },
  };
}
```

**Configure.** In the Function App, open **Settings → Environment variables** and add the settings from the table above as app settings. For the three credentials, use [Key Vault references](https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references) rather than pasting the values.

**Deploy.** From the project folder:

```sh
npm install
func azure functionapp publish <your-function-app-name>
```

Your webhook URL is:

```
https://<your-function-app-name>.azurewebsites.net/api/mitti
```

**De-duplication store.** The adapter uses the Function App's own storage account (the `AzureWebJobsStorage` setting) and creates a table named `mittiseen` the first time it runs. Each alerted issue adds one small row, and rows older than 24 hours are ignored. Table Storage does not delete them automatically, so clear old rows occasionally if the volume matters to you. If your app uses identity-based storage and has no connection string, set `SEEN_STORAGE_CONNECTION` to a storage account connection string instead.

{% hint style="info" %}
The trigger uses `authLevel: 'anonymous'` because Mitti authenticates itself with its HMAC signature, and the receiver rejects anything that fails the check. For a second layer, change it to `'function'` and register the webhook URL with `?code=<function key>` on the end.
{% endhint %}

**Logs.** Use **Monitoring → Log stream**, or Application Insights if you have it enabled.
{% endtab %}

{% tab title="AWS Lambda" %}
This adapter handles a **Lambda Function URL** (payload format 2.0) and stores de-duplication records in **DynamoDB**.

**1. Create the DynamoDB table.** Create a table named `mitti-seen` with partition key `pk` (type String). Enable **Time to Live** on an attribute named `expires`.

**2. Create the function.** Create a Lambda function using the **Node.js 22.x** runtime and set the handler to `lambda.handler`. Upload a zip containing the two files below. The AWS SDK for JavaScript v3 is included in the Node.js runtime, so there is nothing to install.

```
lambda.js      <- the adapter, below
receiver.js    <- the core, from above
```

`lambda.js`:

```javascript
// lambda.js
// AWS Lambda (Function URL, payload format 2.0) adapter for the Mitti -> Relay receiver.
const { DynamoDBClient, GetItemCommand, PutItemCommand } = require('@aws-sdk/client-dynamodb');
const { handle } = require('./receiver');

// De-duplication store: DynamoDB table with partition key "pk" (String) and a TTL attribute
// named "expires". Set the SEEN_TABLE environment variable to the table name.
const table = process.env.SEEN_TABLE;
const ddb = table ? new DynamoDBClient({}) : undefined;
const seen = table
  ? {
      async get(key) {
        const out = await ddb.send(new GetItemCommand({ TableName: table, Key: { pk: { S: key } } }));
        const expires = Number(out.Item?.expires?.N || 0);
        return out.Item && expires * 1000 > Date.now() ? out.Item.value?.S || '1' : null; // DynamoDB TTL deletes lazily, so check expiry here
      },
      async put(key, value, { expirationTtl }) {
        await ddb.send(
          new PutItemCommand({
            TableName: table,
            Item: {
              pk: { S: key },
              value: { S: String(value) },
              expires: { N: String(Math.floor(Date.now() / 1000) + expirationTtl) },
            },
          }),
        );
      },
    }
  : undefined;
if (!seen) console.warn('SEEN_TABLE is not set; de-duplication is in-memory only.');

exports.handler = async (event) => {
  const method = event.requestContext?.http?.method || 'POST';
  // The signature is computed over the raw body, so decode it exactly as sent.
  const body = event.isBase64Encoded ? Buffer.from(event.body || '', 'base64').toString('utf8') : event.body || '';

  const request = new Request(
    `https://${event.requestContext?.domainName || 'lambda-url.invalid'}${event.rawPath || '/'}`,
    { method, headers: event.headers || {}, body: method === 'GET' || method === 'HEAD' ? undefined : body },
  );

  const res = await handle(request, { ...process.env, SEEN: seen });
  return {
    statusCode: res.status,
    headers: { 'content-type': 'application/json' },
    body: await res.text(),
  };
};
```

**3. Configure.** Add the settings from the table above as environment variables, plus `SEEN_TABLE` set to `mitti-seen`. Set the function **timeout to 30 seconds**. The default of 3 seconds is too short, because each delivery makes two outbound API calls. For the three credentials you can read them from AWS Secrets Manager instead of using plain environment variables if your policy requires it.

**4. Allow table access.** Attach a policy to the function's execution role that allows `dynamodb:GetItem` and `dynamodb:PutItem` on the `mitti-seen` table.

**5. Create the Function URL.** On the function's **Configuration → Function URL** page, create a URL with auth type **NONE**. Mitti cannot sign requests with AWS credentials, so the receiver authenticates Mitti with its HMAC signature instead. Your webhook URL is the function URL, which looks like:

```
https://<url-id>.lambda-url.<region>.on.aws/
```

{% hint style="info" %}
AWS requires both `lambda:InvokeFunctionUrl` and `lambda:InvokeFunction` permissions to invoke a function URL. If you create the URL with infrastructure-as-code or the CLI rather than the console, make sure the function's resource-based policy grants both for public access.
{% endhint %}

**De-duplication store.** Each alerted issue adds one item to `mitti-seen` that expires after 24 hours. DynamoDB deletes expired items lazily, sometimes well after expiry, so the adapter also checks the expiry time itself.

**Logs.** Output goes to the function's CloudWatch log group.
{% endtab %}

{% tab title="Cloudflare Workers" %}
This adapter runs as a **Cloudflare Worker** and stores de-duplication records in **Workers KV**.

Project files:

```
worker.js        <- the adapter, below
receiver.js      <- the core, from above
wrangler.toml
```

`worker.js`:

```javascript
// worker.js
// Cloudflare Workers adapter for the Mitti -> Relay receiver.
import { handle } from './receiver.js';

export default {
  async fetch(request, env) {
    return handle(request, env); // bind a KV namespace named SEEN for de-duplication
  },
};
```

`wrangler.toml`:

```toml
name = "mitti-relay-food-safety"
main = "worker.js"
compatibility_date = "2025-01-01"

[vars]
RELAY_GROUP = "food-safety"
FOOD_SAFETY_CATEGORIES = "Food safety"

# After running `npx wrangler kv namespace create SEEN`, add the binding it prints:
# [[kv_namespaces]]
# binding = "SEEN"
# id = "<your-namespace-id>"
```

**Configure.** Store the credentials as secrets:

```sh
npx wrangler secret put MITTI_WEBHOOK_SECRET
npx wrangler secret put MITTI_API_TOKEN
npx wrangler secret put RELAY_SUBSCRIBER_ID
npx wrangler secret put RELAY_API_KEY
```

**De-duplication store.** Create a KV namespace and add the binding it prints to `wrangler.toml` (the commented `kv_namespaces` block):

```sh
npx wrangler kv namespace create SEEN
```

**Deploy:**

```sh
npx wrangler deploy
```

The URL it prints (for example `https://mitti-relay-food-safety.<your-account>.workers.dev`) is your webhook destination.

**Logs.** Run `npx wrangler tail`.
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Hosting somewhere else?** The core only needs a `Request`-like object (`method`, `headers.get()`, `text()`) and an object of settings. Write a short adapter for your platform that builds the request, calls `handle(request, env)`, and returns the response, as the adapters above do. Read the raw request body for signature checking, and do not let your framework parse and re-serialize the JSON before it reaches the receiver.
{% endhint %}

Note the public HTTPS URL for your platform. It is the webhook destination in the next step.
{% endstep %}

{% step %}

## Register the Mitti webhook

Register the receiver's URL from Step 6 for the **Issue created** event:

```sh
curl -X POST \
  -H "Authorization: Bearer $MITTI_API_TOKEN" \
  -H "Content-Type: application/json" \
  "https://api.mitti.com/webhooks/v1/webhooks" \
  -d '{
    "trigger_events": ["TRIGGER_EVENT_INCIDENT_CREATED"],
    "url": "https://<your-receiver-url>"
  }'
```

The response includes the new `webhook_id` and `"enabled": true`. To confirm the registration at any time, list your webhooks:

```sh
curl -H "Authorization: Bearer $MITTI_API_TOKEN" \
  "https://api.mitti.com/webhooks/v1/webhooks"
```

{% hint style="info" %}
Webhooks are set up at the **organization** level. Any Issue created in the top-level organization triggers it, regardless of who created it. The receiver's category filter is what narrows this down to food safety.
{% endhint %}
{% endstep %}

{% step %}

## Test it end to end

In the Mitti app, create a new **Issue**:

1. Give it a title such as `Walk-in cooler reading 52F`.
2. Set the **category** to `Food safety`.
3. Set a **site**, if your organization uses sites. The site name is spoken in the alert.
4. Save the issue.

Within a few seconds a device in your Workflow Group should speak:

> Food safety alert at Store 12 Downtown. Walk-in cooler reading 52F. Please respond.

Tap the talk button to acknowledge. The device that accepts hears *Accepted. You are responding to the food safety alert at Store 12 Downtown.* and the other devices in the group stop alerting.

To confirm from the receiver side, check its logs (Log stream or Application Insights on Azure, CloudWatch on AWS, `npx wrangler tail` on Cloudflare). A successful run logs:

```
Relay alert sent for issue <issue id>, task_id=Q55jJRTWi3zPYtcFAaI5cD
```

Then create a second Issue with a different category, such as `Maintenance`. No alert should sound, and the log shows the issue was ignored.
{% endstep %}
{% endstepper %}

***

## How the receiver behaves

| Situation                          | Receiver response | What happens                                                                       |
| ---------------------------------- | ----------------- | ---------------------------------------------------------------------------------- |
| Valid food safety issue            | `200`             | One Relay alert is sent and the issue is remembered.                               |
| Same issue delivered again         | `200`             | Ignored as a duplicate. No second alert.                                           |
| Issue in a different category      | `200`             | Ignored. Mitti does not retry.                                                     |
| Any event other than Issue created | `200`             | Ignored.                                                                           |
| Signature missing or wrong         | `401`             | Rejected before any outbound call.                                                 |
| Mitti API or Relay API call fails  | `502`             | Mitti retries. The issue is not remembered, so the retry can still send the alert. |

Mitti retries a failed delivery **up to 4 times, 100 seconds apart**, when the receiver returns a 4xx or 5xx response. Delivery is best-effort and events can arrive out of order, so the receiver is built to be safe to call repeatedly. That is why ignored events return `200`: a `4xx` for an issue you intentionally skip would only cause pointless retries.

{% hint style="warning" %}
Webhook delivery is not guaranteed. For a safety-critical process, periodically reconcile against Mitti's [List Issues](https://developer.mitti.com/reference/incidentsservice_getincidents) endpoint to catch any issue that never produced an alert.
{% endhint %}

***

## Customizing the alert

### Which issues page the team

The `FOOD_SAFETY_CATEGORIES` setting takes a comma-separated list, so one receiver can cover several categories:

```
FOOD_SAFETY_CATEGORIES = "Food safety, Hygiene, Pest control"
```

Categories are matched by name, ignoring case. They must match the category names in your Mitti organization exactly (apart from case).

### Different groups for different sites or categories

To route alerts to different Relay Workflow Groups, replace the `groups: [env.RELAY_GROUP || 'food-safety']` line with a lookup based on `issue.task?.site?.name` or `issue.category?.key`. Each value must match a Workflow Group name (or URN) in Relay Dash.

### Other Mitti events

The same receiver pattern works for other webhook events. For example, `TRIGGER_EVENT_ACTION_CREATED` covers new corrective actions, and `TRIGGER_EVENT_INSPECTION_COMPLETED_STATUS` covers completed inspections. Each event needs its own fetch-and-filter logic, because the webhook itself only carries identifiers. See [Supported webhook trigger events](https://developer.mitti.com/reference/webhooks#supported-webhook-trigger-events).

***

## Payload reference

### Mitti webhook envelope

Every Mitti webhook uses the same outer structure. The receiver uses the fields marked below.

| Field                  | Used for                                                                         |
| ---------------------- | -------------------------------------------------------------------------------- |
| `webhook_id`           | Identifies the webhook registration.                                             |
| `event.event_types`    | List of event types. The receiver acts only on `TRIGGER_EVENT_INCIDENT_CREATED`. |
| `event.date_triggered` | When the event occurred.                                                         |
| `resource.id`          | The ID of the issue. The receiver fetches the full issue with it.                |
| `resource.type`        | The kind of resource the event refers to.                                        |

### Mitti fields used from Get Issue

The receiver calls `GET https://api.mitti.com/tasks/v1/incident/{id}` (the [Get Issue](https://developer.mitti.com/reference/incidentsservice_getincidentbyid) endpoint) and reads:

| Field                     | Used for                                           |
| ------------------------- | -------------------------------------------------- |
| `incident.category.key`   | Matched against `FOOD_SAFETY_CATEGORIES`.          |
| `incident.task.title`     | Spoken as the problem description.                 |
| `incident.task.site.name` | Spoken as the location, when the issue has a site. |

In the Mitti API, Issues were previously called Incidents, so you will see `incident` in endpoint paths and response fields. They are the same thing.

### Relay alert keys

`notification` and `groups` are required. Everything else is optional.

| Key            | Type          | Default                      | Behavior                                                                                              |
| -------------- | ------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `notification` | string        | —                            | Spoken on every device in the group via text-to-speech.                                               |
| `groups`       | array         | —                            | Workflow Group names or URNs to alert.                                                                |
| `quorum`       | integer       | all devices must acknowledge | Cancels remaining alerts after this many acknowledgements. **Set this to `1` for food safety calls.** |
| `on_ack`       | string        | nothing spoken               | Spoken on the device that acknowledged.                                                               |
| `on_quorum`    | string        | nothing spoken               | Spoken on devices that had not yet acknowledged once quorum is met.                                   |
| `timeout`      | integer (sec) | `300`                        | Cancels remaining alerts after this long.                                                             |
| `on_timeout`   | string        | nothing spoken               | Spoken on devices that never acknowledged, after timeout.                                             |
| `name`         | string        | `alerts`                     | Controls serial/concurrent alerting behavior and appears in analytics events for correlation.         |

Leaving `quorum` at its default means the alert keeps sounding on every other device until **all** of them acknowledge. That is not what you want when one person takes the job. Set `quorum: 1`.

{% hint style="warning" %}
**Write for text-to-speech, not for a log file.**

Issue titles are typed by people and can contain codes, symbols, and punctuation that sound like gibberish when spoken. The receiver keeps only letters, digits, spaces, and `. , ' -`, collapses extra whitespace, and cuts the title at 120 characters. Do not add the issue description or free-text fields to the spoken message.
{% endhint %}

{% hint style="info" %}
The receiver builds the Relay request body with `JSON.stringify()`, so a double quote, backslash, or newline in an issue title cannot produce invalid JSON. If you adapt this code to build the body by string concatenation instead, those characters will cause Relay to reject the request with a 400.
{% endhint %}

***

## Troubleshooting

Start with the receiver's logs. Every delivery produces one log line or one JSON response.

| Symptom                                                        | Likely cause and fix                                                                                                                                                                                                                                                                                                               |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No requests reach the receiver at all                          | The webhook is not registered, is disabled, or points at the wrong URL. List your webhooks (Step 7) and check `enabled` and `url`. Confirm the token that registered it had the permissions in Step 4.                                                                                                                             |
| Receiver returns `401 Invalid signature`                       | The `MITTI_WEBHOOK_SECRET` is wrong or was regenerated, or the body was altered before verification. Fetch the secret again (Step 5), and make sure nothing parses and re-serializes the JSON before the signature check.                                                                                                          |
| Receiver returns `502 Could not fetch issue`                   | The Mitti API token is wrong, expired from inactivity, or its owner cannot access the issue. Check the status code in the log. Include **Manage all data** on a service user token so it can read every issue.                                                                                                                     |
| Log says `Ignored: category ... is not a food safety category` | The issue's category does not match `FOOD_SAFETY_CATEGORIES`. Compare against the exact category name in Mitti.                                                                                                                                                                                                                    |
| Receiver returns `502 Relay alert failed`                      | Check the logged Relay status. `401` means the `RelayApiKey` header or key is wrong, and `404` usually means a wrong subscriber ID. Run the curl from Step 3 with the same values.                                                                                                                                                 |
| Log says `Relay alert sent`, but no device speaks              | The alert was accepted, so check the Relay side. `RELAY_GROUP` must exactly match a Workflow Group name, and that group must have members whose devices are online.                                                                                                                                                                |
| The alert keeps repeating after someone started work           | Alerts repeat every 30 seconds until acknowledged on a device or until `timeout`. Acknowledge on the device, or cancel with the `DELETE` call in Step 3.                                                                                                                                                                           |
| Two alerts for one issue                                       | The receiver is falling back to its in-memory store across multiple instances. Check that the platform's store is configured (Table Storage connection on Azure, `SEEN_TABLE` and table permissions on AWS, the `SEEN` KV binding on Cloudflare). The Azure and AWS adapters log a warning at startup when their store is missing. |

{% hint style="success" %}
If the curl command in Step 3 works but the integration does not, the problem is in Mitti or the receiver, not in Relay.
{% endhint %}

***

## Reference

### Mitti

* [Webhooks](https://developer.mitti.com/reference/webhooks)
* [Create a webhook](https://developer.mitti.com/reference/webhooksservice_createwebhook)
* [Get signature secret](https://developer.mitti.com/reference/webhooksservice_gettoken)
* [Issues](https://developer.mitti.com/reference/issues)
* [Get Issue](https://developer.mitti.com/reference/incidentsservice_getincidentbyid)
* [Authentication](https://developer.mitti.com/reference/authentication)

### Relay

* [Alerts overview](https://developer.relaypro.com/docs/relay-alerts-api)
* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)
