This document describes how HazardWatch is put together: the moving parts, how data flows between them and the principles that guide new code. The reasoning behind individual choices lives in the architecture decision records.
HazardWatch is a TypeScript monorepo with two deployable applications that share one PostgreSQL database.
flowchart LR
feeds["Open data feeds<br/>USGS, NASA FIRMS, GDACS"]
browser(("Browser"))
tiles["OpenFreeMap<br/>vector tiles"]
imagery["NASA GIBS<br/>satellite imagery"]
smtp["SMTP server<br/>Mailpit in development"]
pushService["Browser push services"]
subgraph worker ["apps/worker"]
scheduler["Scheduler"] --> adapters["Source adapters"]
adapters --> repository["Ingestion repository"]
scheduler --> notifier["Alert emails"]
scheduler --> pusher["Alert notifications"]
end
subgraph web ["apps/web (Next.js)"]
pages["Server components"]
actions["Server actions"]
authApi["/api/auth/*<br/>Better Auth"]
health["/api/health"]
end
subgraph database ["PostgreSQL + PostGIS"]
events[("hazard_events")]
runs[("ingestion_runs")]
zones[("watch_zones")]
alerts[("zone_alerts")]
subscriptions[("push_subscriptions")]
authTables[("user, session,<br/>account, verification")]
end
feeds -- "HTTP polling" --> adapters
repository --> events
repository --> runs
repository -- "matches zones" --> alerts
notifier -- "claims" --> alerts
notifier -- "alert digests" --> smtp
pusher -- "claims" --> alerts
pusher -- "reads" --> subscriptions
pusher -- "notifications" --> pushService
pushService -- "push" --> browser
browser --> pages
browser --> actions
browser --> authApi
browser -- "basemap" --> tiles
browser -- "imagery" --> imagery
pages --> events
pages --> runs
pages --> zones
pages --> alerts
actions --> zones
actions --> alerts
actions --> subscriptions
authApi --> authTables
authApi -- "address confirmations" --> smtp
| Package | Responsibility |
|---|---|
apps/web |
User-facing application: pages, authentication, HTTP endpoints |
apps/worker |
Long-running process that polls hazard feeds and stores events |
packages/db |
Database schema, client factory, migrations and shared types |
packages/email |
SMTP sending and the templates of every email |
Applications depend on packages, never on each other. The database is the only integration point between the web app and the worker.
- Next.js App Router. Pages are React Server Components that read from
the database through
@hazardwatch/db. There is no internal REST layer for reads; route handlers exist only where an HTTP endpoint is required. - Authentication. Better Auth handles email and password accounts.
Sessions are stored in PostgreSQL through the Drizzle adapter, with a
short-lived signed cookie cache to avoid a database lookup per request.
requireSession()guards protected pages and the(auth)route group redirects users who are already signed in. A link sent on sign-up confirms the address, which alert emails require (see ADR 0009); until then, the dashboard and the alerts page offer a new link. A forgotten password is reset through a link valid for one hour, which works once and signs every other session out. - Endpoints.
/api/auth/*is mounted by Better Auth./api/healthchecks database connectivity and returns503when it is unreachable, so it can back a load balancer or uptime probe. - Configuration. Environment variables are validated with zod when the
server starts. Server-only modules import
server-onlyso they can never end up in a client bundle. - Home page.
/is public and rendered on every request. It reads the events active in the past 24 hours, counts them by kind and hands them to a canvas that draws the planet as a seismogram: one line per band of latitude, raised over land from a Natural Earth mask bundled with the app, with a peak at every event. The feature tiles show NASA imagery fetched by the browser. Without the database, the page renders without live data. - Live map.
/mapis public. The page reads its filters (hazard type, period and minimum severity) from the URL, queries the matching events active during the period, most recently active first and capped at 2,000, and hands them to a client component that renders them with MapLibre GL on OpenFreeMap tiles (see ADR 0005). The map is a globe, and its basemap can show NASA satellite imagery instead: the latest complete day, clouds over the Americas every ten minutes, or city lights at night (see ADR 0012). The browser fetches the imagery from NASA directly and remembers the chosen basemap. Events merge into clusters, coloured by their most severe event, until the map shows about a country. Fires add their heat below the markers, and events that started in the past six hours pulse, still for users who prefer reduced motion. The card of a selected event shows the area around it seen by NOAA-20 on its last day of activity, a still image the browser asks GIBS for, with its fire detections and coastlines. Its arrows go back and forth in days, and an empty picture, where the satellite missed the place, gives way to the day before. Changing a filter navigates to a new URL, and the page callsrouter.refresh()every minute while visible. Both re-render on the server and keep client state such as the map position and the selected event. - Watch zones. Signed-in users manage the circles they watch from
/zones(see ADR 0007). The list sums up the past 7 days for each zone, and each zone has a page that reuses the live map, limited to the events located within it. Zones are created, edited and deleted through server actions, which check the session, validate the input with zod and only ever touch the signed-in user's zones. - Alerts.
/alertslists the alerts raised for the user's zones, and the header shows how many are unread. Opening an alert goes through a server action that marks it as read, then shows the event on its zone's map. A plain link would be prefetched and mark alerts as read on its own. - Push notifications. When
VAPID_PUBLIC_KEYis set, the alerts page lets the user turn notifications on for the current device. It registers/sw.js, a service worker that shows the notifications the worker pushes and opens the page they point to, and saves the browser's subscription through a server action (see ADR 0013). Signing out removes the current browser's subscription. A web app manifest makes the app installable, which iPhones require for notifications. - Code shared with the browser. Client components import domain values
from
@hazardwatch/db/constants, a dependency-free entry point. The main entry point pulls in Drizzle and the PostgreSQL driver and is reserved for server code.
- Sources. Each upstream feed is an adapter implementing the
Sourceinterface: an identifier, a polling interval and afetchEventsfunction that returns events in the normalised shape. Feed-specific formats never leave the adapter. Adapters validate upstream payloads with zod: a malformed record is logged and skipped, while an unrecognisable payload fails the run. A source whose feed only covers a recent window declares itself windowed, so that its lasting events keep their start. - HTTP. Requests go through a shared helper that combines a timeout with the shutdown signal, so a stalled server cannot block a source.
- Scheduler. Every source is polled on its own interval. The next run for a source starts only after the previous one has finished, so a slow feed cannot pile up concurrent requests.
- Runs. Each pass is recorded in
ingestion_runswith its outcome, the number of events written and any error. Failures are recorded rather than thrown, so one broken feed never stops the others. - Writes. Events are upserted in batches keyed on
(source, external_id). Fetching the same feed twice is a no-op, and events revised upstream are updated in place. When a source reports a revision time, unchanged events are not rewritten at all. - Alerts. In the transaction that writes a batch, the events inserted or revised are matched against every watch zone, and an alert is recorded for each zone an event reaches at or above the zone's threshold (see ADR 0008). Alerts are raised once per zone and event, and again when the event grows more severe or starts again. Events that ended more than a day ago raise none.
- Alert emails. Every two minutes, the worker claims the alerts waiting
to be emailed and sends each user one message listing theirs (see
ADR 0009).
Claiming locks rows with
FOR UPDATE SKIP LOCKED, so concurrent workers never send the same alert, and a failed message puts its alerts back in the queue. WithoutSMTP_URL, this task does not run. - Alert notifications. Every minute, the worker claims the unread alerts
raised in the past hour for users with a subscribed browser, and pushes
each user one notification to each of their browsers with
web-push(see ADR 0013). Browsers whose push service says they are gone are forgotten, and alerts no browser could take go back in the queue. Without the VAPID keys, this task does not run. - Health endpoint. When
PORTis set, the worker answers health checks on/health, for hosts that run it as a web service, such as Render's free plan (see ADR 0010). - Lifecycle.
SIGINTandSIGTERMabort pending waits, close the health endpoint and the connection pool, which keeps restarts and deployments clean.
| Source | Feed | Polled every | Hazard kinds |
|---|---|---|---|
usgs |
Magnitude 2.5+ earthquakes worldwide, past 24 hours | 1 minute | Earthquake |
gdacs |
Disaster alerts modified in the past two days | 10 minutes | Tropical cyclone, flood, volcano, drought and wildfire |
nasa_firms |
Fire detections by satellite, past 24 hours | 30 minutes | Wildfire |
USGS. The summary feed is regenerated every minute and covers a sliding 24-hour window, so the worker catches up on its own after a short outage. Other seismic events, such as quarry blasts, are ignored. Severity combines the magnitude with the PAGER alert level, which estimates human and economic impact, and keeps the higher of the two:
| Severity | Magnitude | PAGER alert |
|---|---|---|
minor |
below 5.0 | green |
moderate |
5.0 to 5.9 | yellow |
severe |
6.0 to 6.9 | orange |
extreme |
7.0 and above | red |
GDACS. The Global Disaster Alert and Coordination System assesses the humanitarian impact of disasters worldwide. The worker pages through the event list API for every event modified during the past two days, so revisions are applied in place and an outage of up to two days is caught up. GDACS also reports earthquakes, but it takes them from USGS, so they are left out to avoid duplicates.
A few quirks of the API are handled in the adapter:
- Timestamps are in UTC but carry no time zone designator.
- A query that matches nothing, including a page past the last one,
answers
404rather than an empty list. - The list can shift between two page requests, so an event may be listed twice in one run. The most recently modified copy is kept, since an upsert cannot touch the same row twice.
Each event is located at the centroid of the affected area. It is active
from its fromdate to its todate, which moves forward as GDACS updates
the event. Severity follows the event's alert level, which estimates
whether international assistance will be needed, on the same colour scale
as PAGER:
| Severity | GDACS alert | International assistance |
|---|---|---|
minor |
green | Unlikely |
severe |
orange | Possibly needed |
extreme |
red | Likely needed |
NASA FIRMS. FIRMS publishes the fire detections of the past 24 hours by the VIIRS instruments of the NOAA-20 and NOAA-21 satellites, as public CSV files that need no API key. That is about 100,000 detections a day, so the adapter groups them into fires, one per cell of a 0.25° grid, about 28 km (see ADR 0011).
- A HEAD request reads when each file changed, since NASA's server ignores conditional requests, and the files are only downloaded when one did.
- Low-confidence detections are ignored. A cell's power is the highest total fire radiative power seen by one satellite, so that a fire seen by both is not counted twice.
- Each fire is located at the centre of its detections and active from the first to the last of them. The source is windowed, so a fire that keeps burning keeps its start.
Severity follows the power in a cell. Cells below 250 MW, mostly small agricultural burns, are left out:
| Severity | Power in a cell |
|---|---|
minor |
250 MW |
moderate |
500 MW |
severe |
1,000 MW |
extreme |
2,500 MW |
- Schema. Drizzle table definitions are the single source of truth for the database structure and the TypeScript types derived from it.
- Migrations.
drizzle-kitgenerates SQL migrations that are reviewed and committed alongside the schema change. They are applied explicitly withpnpm db:migrate, never implicitly when an application starts. - Shared runtime. The package re-exports the Drizzle query helpers it
uses so that every application resolves a single
drizzle-orminstance, along with conditions both applications rely on, such as the one that matches events to watch zones. - Testing.
@hazardwatch/db/testingcreates a temporary, migrated database for integration tests and drops it afterwards. Run them withpnpm test:integrationwhile the database container is up.
- Sending.
createMailerwraps a Nodemailer SMTP transport behind a smallMailerinterface, which tests replace with a fake. - Templates. Every email has a plain text and an HTML version, built from a shared layout with inline styles. Values that come from users or feeds are escaped.
- Development. Mailpit, started by
docker compose, accepts SMTP on port 1025 and shows every message on http://localhost:8025.
| Table | Purpose |
|---|---|
hazard_events |
Normalised events from every source, one per upstream event |
ingestion_runs |
Audit trail of each polling pass, used for monitoring |
watch_zones |
Areas watched by each user, as a centre and a radius |
zone_alerts |
Events that reached a zone, one per zone and event |
push_subscriptions |
Browsers that receive a user's alerts as notifications |
user, session, account, verification |
Better Auth accounts and sessions |
hazard_events stores its position as a PostGIS geometry(Point, 4326)
(WGS 84 longitude and latitude) with a GiST index, so that proximity and
containment queries stay fast as the table grows. Fields shared by every
source are proper columns; anything source-specific is kept in a jsonb
properties column rather than widening the table.
Each event is active from occurred_at until active_until. The two are
equal for instantaneous events such as earthquakes, while lasting events
such as floods extend active_until with every update. Time windows match
events on active_until, so an event that started long ago but is still
going on is included (see ADR 0006).
A windowed source, such as FIRMS, only sees the recent part of a lasting
event, so the repository keeps the stored occurred_at while the event goes
on. Activity seen after more than two days of silence starts the event
again, with a new occurred_at.
A watch zone covers every point within radius_km of its center. Events
are matched with ST_DWithin on the geography type, so that distances are
measured on the Earth's surface, and a GiST index on the event location
cast to geography keeps these queries fast. Zones are deleted along with
their owner's account.
Each zone has an alert threshold, alert_min_severity, which is null when
the user wants no alerts. An alert keeps the severity it was last raised
with, so that only a more severe revision raises it again, and read_at
records when the user read it. Alerts are deleted with their zone or their
event.
watch_zones.email_alerts says whether a zone's alerts are also emailed,
and zone_alerts.emailed_at when an alert was handed to the email server.
Alerts still waiting have none, and a partial index on them keeps the
worker's lookup small. zone_alerts.pushed_at works the same way for push
notifications.
A push subscription holds what the Push API gives for a browser: the endpoint of its push service, unique to that browser, and the keys that encrypt messages for it. Subscriptions are deleted with their owner's account.
sequenceDiagram
participant S as Scheduler
participant A as Source adapter
participant F as Upstream feed
participant D as PostgreSQL
loop every source.intervalMs
S->>D: insert ingestion_runs (running)
S->>A: fetchEvents(signal)
A->>F: GET feed
F-->>A: payload
A-->>S: normalised events
S->>D: upsert hazard_events on (source, external_id)
S->>D: insert zone_alerts for the zones the changed events reach
S->>D: update ingestion_runs (succeeded or failed)
end
All applications read a single .env file at the repository root in
development. In production the same variables come from the hosting
platforms: Vercel for the web app and Render for the worker, as described
in the deployment guide.
| Variable | Used by | Description |
|---|---|---|
DATABASE_URL |
web, worker | PostgreSQL connection string |
BETTER_AUTH_SECRET |
web | Secret used to sign session cookies |
BETTER_AUTH_URL |
web | Public URL of the web application |
SMTP_URL |
web, worker | SMTP server for outgoing email. No email is sent without it |
EMAIL_FROM |
web, worker | Sender of every email, as Name <address> |
APP_URL |
worker | Public URL of the web application, for links in alert emails |
VAPID_PUBLIC_KEY |
web, worker | Public key of push notifications. None are offered without it |
VAPID_PRIVATE_KEY |
worker | Private key that signs push notifications |
VAPID_SUBJECT |
worker | Contact for push services. Defaults to APP_URL over https |
LOG_LEVEL |
worker | fatal, error, warn, info (default), debug or trace |
PORT |
worker | Optional port of the health endpoint, set by the host |
- Normalise at the edge. Adapters translate upstream payloads into one event shape. The rest of the system only ever deals with that shape.
- Make writes idempotent. Any job may run twice; the outcome must be the same.
- Isolate failures. An unavailable feed or a malformed payload affects one run of one source, nothing more.
- Fail fast on configuration. Invalid environment variables stop the process at startup with a readable message, not at the first request.
- Keep boundaries explicit. Code shared between applications lives in a package with a deliberate public API.