# Cronitor monitor failed or recovered notifications on your phone

> Get a push notification when a Cronitor cron job, heartbeat or website check fails, and a quiet one when it recovers.

- Company: Cronitor (https://www.justpush.io/recipes/cronitor)
- Event: `alert` (Webhooks)
- Tags: Monitoring & observability, Cron & background jobs, Uptime & downtime
- Install: https://studio.justpush.io/recipes/cronitor/monitor-alert
- Web page: https://www.justpush.io/recipes/cronitor/monitor-alert

## Setup

1. Click Install in Studio and sign in. The recipe is added to your account and you get a personal webhook URL.
2. In Cronitor, open Settings > Integrations, click Create Integration and select Webhooks.
3. Give it a name and identifier, paste your webhook URL (shown in Studio after install) as the URL and press Create Integration.
4. Add the integration to the Notification Lists your jobs and monitors use.
5. In Cronitor, open **Settings → Integrations**, click **Create Integration** and select **Webhooks**. Give it a name and a unique identifier, paste the URL above and press **Create Integration**. Webhooks are available on every plan, including the free Hacker plan.
6. Then add the integration to one or more **Notification Lists** (Settings → Alerts). Every job, heartbeat or check that uses those lists will send a push when it fails and a quiet one when it recovers.
7. Optional query parameters on the URL:
8. `?env=production` only pushes alerts from that Cronitor environment.
9. `?urgent=1` sends failures at Highest priority instead of High, e.g. for a list that only holds website checks.
10. Combine them with `&`, e.g. `your webhook URL (shown in Studio after install)?env=production&urgent=1`.
11. **Testing:** Cronitor has no test button for webhooks. Create a heartbeat monitor on the same notification list, open its telemetry URL once, then again with `?state=fail` added (an alert), then once more without it (a recovery).
12. Cronitor's docs list the payload fields (`id`, `monitor`, `description`, `type`, `rule`, `environment`, `group`, `issue_url`, `monitor_url`) but don't show an example, request headers or signing, so the wording of `description` and `rule` in `sample.json` is illustrative. Keep your endpoint URL private.

## Code

Studio calls `handleRequest(request)` with the incoming webhook (`{ method, headers, body, query, raw }`) and sends the message object it returns. Returning `null` sends nothing.

```js
// Cronitor → monitor alert or recovery
// Fires when a Cronitor job, heartbeat or check fails (type ALERT) and when it becomes
// healthy again (type RECOVERY), via a Webhooks integration on a Notification List.
// Docs: https://cronitor.io/docs/using-webhooks

// Webhook "type" values we handle (Cronitor documents RECOVERY|ALERT).
const TYPES = {
    ALERT: "alert",
    RECOVERY: "recovery",
}

// Look up a key without tripping over inherited names like "toString".
function pick(table, key, fallback) {
    return typeof key === "string" && Object.prototype.hasOwnProperty.call(table, key) ? table[key] : fallback
}

// Only link to real http(s) URLs.
function link(url, cta) {
    return typeof url === "string" && /^https?:\/\//.test(url) ? [{ cta, url }] : []
}

// A trimmed string, or null for anything empty or not text-like.
function text(value) {
    if (typeof value !== "string" && typeof value !== "number") return null
    const s = String(value).trim()
    return s ? s : null
}

// "1", "true" or "yes" in the query string.
function flag(request, name) {
    return ["1", "true", "yes"].includes(String(request.query?.[name] ?? "").toLowerCase())
}

function handleRequest(request) {
    const body = request.body && typeof request.body === "object" && !Array.isArray(request.body) ? request.body : {}
    const kind = pick(TYPES, text(body.type)?.toUpperCase(), null)
    const name = text(body.monitor) ?? text(body.id)

    // Guard: only Cronitor alert/recovery webhooks, which always name a monitor.
    if (!kind || !(name || text(body.monitor_url))) {
        console.log(`Not a Cronitor alert ("${text(body.type) ?? "unknown"}") — skipping`)
        return null
    }

    // ?env=production only pushes alerts from that environment.
    const env = text(body.environment)
    const onlyEnv = text(request.query?.env)
    if (onlyEnv && env && env.toLowerCase() !== onlyEnv.toLowerCase()) {
        console.log(`Skipping Cronitor alert for environment "${env}" (only "${onlyEnv}")`)
        return null
    }

    const monitor = name ?? "Your monitor"
    const context = [text(body.group), env].filter(Boolean)
    const buttons = [...link(body.issue_url, "View issue"), ...link(body.monitor_url, "View monitor")]

    if (kind === "alert") {
        const why = text(body.description) ?? text(body.rule) ?? "It failed a check"
        return {
            title: `🔴 ${monitor} failed`,
            message: [why, ...context].join(" · "),
            topic: "Cronitor",
            // High — a job or site you rely on is failing. ?urgent=1 makes it Highest (2)
            // for monitors where a failure means something is down right now.
            priority: flag(request, "urgent") ? 2 : 1,
            buttons,
        }
    }

    return {
        title: `✅ ${monitor} recovered`,
        message: [text(body.description) ?? "It's healthy again", ...context].join(" · "),
        topic: "Cronitor",
        priority: -1, // Low — back to normal, nothing to do
        buttons,
    }
}
```

## Cronitor alert webhook payload (sample)

```json
{
  "id": "nightly-backup",
  "rule": "job failed",
  "type": "ALERT",
  "group": "Backups",
  "monitor": "Nightly backup",
  "issue_url": "https://cronitor.io/app/issues/a1b2c3d4",
  "description": "Job exited with status code 1",
  "environment": "production",
  "monitor_url": "https://cronitor.io/app/monitors/nightly-backup"
}
```

## FAQ

### Does this work on iPhone and Android?

Yes. Install the JustPush app from the App Store or Google Play and sign in. Every phone signed in to your account gets the notification.

### Do I need to write code?

No. Install the recipe in Studio, paste your webhook URL into Cronitor and you are done. The code is there if you want to change the text, the sound or the buttons.

### Can I change what the notification says?

Yes. After install the recipe's code is yours. Edit it in Studio and test it against the sample payload before you save.

### What does it cost?

JustPush is free for 30 days. After that it's $19.99 a year, or $39.99 once. There is no extra charge for recipes.
