# Free Phone Alerts From Any Script with ntfy

The worst failures are the silent ones: the 2 a.m. backup that stopped working three weeks ago, the cron job that exits with an error nobody reads, the disk that fills up on a Sunday.

[ntfy](https://ntfy.sh) (pronounced "notify") fixes the "nobody told me" part with almost no setup. It's an open-source, HTTP-based publish/subscribe service. Your script sends an HTTP request to a _topic_, and your phone, subscribed to that topic, buzzes. There's no sign-up, no API key, and no SDK to install.

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpFj0FLw0AQhf_KOOeNInjKQWgLoqBYGvXS7WGzmTSrm51ld9Ia2_53SSt4fMPj--Yd0HJDWGLreW87kwSeVzoAAMzWGiubXBTgBDZxgE-uNW6gKO6PGu2QPCxfqze46cdCODqr8QjztcYg7QiZ0o5SCVO4zt0EyeTbouMs1GjcXDTzP1wccgeBxbXOGnEcJthirXHZcSAwMUIe6myTq6kBYfiXblBhT6k3rsHygNJRP01qqDWDF1SXy4dJztSe8tRpOciD6Z0fscTCxOipyGMW6hXMvQtfL8ZW5_zAQRRorGjLBO9PGhWsuGZhBY_kdyTOGgWz5IxXkE3IRabkWlRnSeV-pl9u7-I3nk4K6-2CPScs8WrfOSE8_QLAboLg?type=png)

## Your first alert in 60 seconds

1.  Install the ntfy app (Android or iOS) and subscribe to a topic name. A web app is also available.
    
2.  From any terminal:
    

```bash
curl -d "Backup successful" ntfy.sh/my-topic
```

Your phone buzzes. Topics are created on the fly, so there's nothing to set up first.

> **Important:** on the public server the topic name is effectively the password. Anyone who knows or guesses it can read and publish to it. Don't use `alerts` or `backups`; use something random, like `alerts-$(openssl rand -hex 8)`. See "Locking it down" below for the proper fix.

## Make alerts useful with headers

A bare message is fine for testing. A few headers turn it into something you can triage at a glance:

```bash
curl \
  -H "Title: Disk almost full" \
  -H "Priority: high" \
  -H "Tags: warning" \
  -H "Click: https://grafana.example.com/d/disk" \
  -d "/var is at 93% on web-1" \
  ntfy.sh/my-topic
```

-   **Title** replaces the default topic-name title.
    
-   **Priority** accepts `min`, `low`, `default`, `high` and `urgent` (or 1 to 5). Higher priorities vibrate and sound more insistently, so reserve `urgent` for things worth waking up for.
    
-   **Tags** are comma-separated; names that match emoji short codes (`warning`, `white_check_mark`, `rotating_light`) show up as emoji.
    
-   **Click** opens a URL when you tap the notification. There are also `Attach`, `Actions` (buttons) and `Email` headers if you need them.
    

## Wire it into your scripts

Put one helper in a file you can `source` everywhere. It has a timeout and swallows its own errors, so a broken notification never breaks the job it's reporting on.

```bash
# ~/bin/notify.sh
NTFY_URL="${NTFY_URL:-https://ntfy.sh}"

notify() {  # usage: notify "Title" "Message" [priority] [tags]
  local auth=()
  [ -n "$NTFY_TOKEN" ] && auth=(-H "Authorization: Bearer $NTFY_TOKEN")
  curl -fsS -m 10 --retry 2 "${auth[@]}" \
    -H "Title: $1" -H "Priority: ${3:-default}" -H "Tags: ${4:-bell}" \
    -d "$2" "$NTFY_URL/$NTFY_TOPIC" > /dev/null || true
}
```

**A backup job that reports its own result:**

```bash
#!/usr/bin/env bash
set -eo pipefail
source ~/bin/notify.sh
export NTFY_TOPIC="alerts-xxxxxxxx"

rc=0
rsync -a --delete ~/data/ backup:/srv/backups/data/ || rc=$?

if [ "$rc" -eq 0 ]; then
  notify "Backup OK" "$(hostname): rsync finished" low white_check_mark
else
  notify "Backup FAILED" "$(hostname): rsync exited with code $rc" urgent warning
fi
```

**Catch _any_ failure in a script with a trap:**

```bash
set -eEo pipefail
trap 'notify "Job failed" "$(basename "$0") failed at line $LINENO" urgent rotating_light' ERR
```

The capital `E` matters: without it, the trap doesn't fire for commands that fail inside functions.

**From Python:**

```python
import os
import requests

NTFY_URL = "https://ntfy.example.com/alerts"
NTFY_TOKEN = os.environ["NTFY_TOKEN"]  # tk_... token; skip the header on an open topic

def notify(msg, title="Script", priority="default"):
    try:
        requests.post(
            NTFY_URL,
            data=msg.encode("utf-8"),
            headers={
                "Title": title,
                "Priority": priority,
                "Authorization": f"Bearer {NTFY_TOKEN}",
            },
            timeout=10,
        )
    except requests.RequestException:
        pass  # never let the alert break the job
```

One habit that pays off: **alert on failure loudly, and on success quietly** (`low` priority). A daily "OK" message that suddenly doesn't arrive is itself a signal.

## Locking it down

The public server has no accounts for anonymous use, so a hard-to-guess topic is your only protection. If you want real access control, you have two options: reserve topics with an account on ntfy.sh, or run your own server.

### Self-hosting

Self-hosting is a single container. Create a `server.yml`:

```yaml
base-url: "https://ntfy.example.com"      # required for attachments, iOS and more
cache-file: "/var/cache/ntfy/cache.db"
auth-file: "/var/lib/ntfy/user.db"
auth-default-access: "deny-all"           # see the warning below
behind-proxy: true
upstream-base-url: "https://ntfy.sh"      # only needed for instant iOS notifications
```

> **Warning:** `auth-default-access` defaults to `read-write`, which means a fresh server lets anyone who can reach it publish and read any topic. Set it to `deny-all` before exposing the server.

Then a `docker-compose.yml`:

```yaml
services:
  ntfy:
    image: binwiederhier/ntfy
    command: serve
    restart: unless-stopped
    ports:
      - "127.0.0.1:2586:80"     # put a reverse proxy with HTTPS in front
    volumes:
      - ./server.yml:/etc/ntfy/server.yml:ro
      - ./cache:/var/cache/ntfy
      - ./lib:/var/lib/ntfy
```

Create users and a token, and give scripts write-only access:

```bash
docker compose up -d
docker compose exec ntfy ntfy user add --role=admin me          # for your phone (asks for a password)
docker compose exec ntfy ntfy user add scripts                  # for your jobs (asks for a password)
docker compose exec ntfy ntfy access scripts 'alerts*' write-only
docker compose exec ntfy ntfy token add scripts                 # prints tk_...
```

Your scripts now authenticate with that token:

```bash
export NTFY_URL="https://ntfy.example.com"
export NTFY_TOKEN="tk_..."
```

A leaked script token can then only _publish_ to `alerts*`. It can't read your notifications or touch other topics.

**iOS note:** Apple only allows push notifications through its own service, so a self-hosted server relays a tiny "poll request" (just a message ID, not the content) via ntfy.sh. That's what `upstream-base-url` enables. The app then fetches the real message from your server. Android doesn't need this.

## Gotchas

-   **Rate limits on the public server.** Free use is limited (a burst of 60 requests, then roughly one every few seconds, plus a daily message cap). A loop that alerts on every failure can hit it, so send one summary per run instead. Limits can change, so check the docs. On your own server there are still default limits per client, but you can raise them in `server.yml` (for example `visitor-request-limit-burst`).
    
-   **Cron has a minimal environment.** Use absolute paths and set `NTFY_TOPIC` and `NTFY_TOKEN` inside the script or the crontab, or your alerts will quietly never fire.
    
-   **Don't send secrets.** Messages pass through the server and your phone's notification system. Send "backup failed on db-1", not the connection string.
    
-   **Message size.** Long bodies (over about 4 KB on the public server) are converted into attachments. Keep alerts short and link to details with `Click`.
    
-   **Non-ASCII titles.** Some HTTP libraries mangle UTF-8 in headers. If you see `?` characters, RFC 2047-encode the header.
    
-   **ntfy tells you when something _ran and failed_, not when it _never ran_.** If the server, the cron daemon or the whole machine is down, nothing gets sent. Pair it with a dead-man's switch such as Healthchecks.io for jobs that must run on schedule.
    

## Wrap-up

ntfy is one of those tools that takes five minutes to adopt and then ends up in every script you write. Start with a random topic and the `notify` helper above. If you end up with more than a handful of jobs, or you want proper access control, move to a self-hosted server with a write-only token for your scripts.

---

*Published via [ZyVOP](https://zyvop.com/free-phone-alerts-from-any-script-with-ntfy-ttgph?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
