9.4 KiB
Counter
A self-hosted calorie counter you run in Docker and use from your phone's browser.
- Scan a barcode with the camera (or take a photo) and pull calories and macros from Open Food Facts. You can also search by name or type the numbers in yourself.
- Track movement: enter steps and workouts; the app estimates what you burned with MET values.
- See the day as one number: calories eaten minus target, with protein, carbs and fat bars.
- Plan meals: generates breakfast, lunch, dinner and a snack that fit your remaining budget, with vegan / vegetarian / high-protein styles.
- Install to the home screen: it is a PWA, so it opens full-screen like an app.
Quick start
cp .env.example .env # optional: set TZ and INGEST_TOKEN
docker compose up -d --build
Open http://localhost:31490 on the machine, or http://<your-server-ip>:31490 on your phone (same network).
Data lives in the counter-data Docker volume (SQLite). To back it up:
docker run --rm -v counter-data:/data -v "$PWD":/backup alpine tar czf /backup/counter-backup.tgz -C /data .
Using it on a phone
- Find the host's LAN address (
hostname -Ion Linux,ipconfig getifaddr en0on macOS). - Open
http://THAT-IP:31490in Safari or Chrome, then Add to Home Screen.
Camera note: browsers only allow live camera access on https:// or localhost. Over plain http://192.168.x.x:31490 the "Start camera" button will refuse, but "Take a photo of the barcode" and typing the barcode both work. For live scanning on the phone, put the app behind a TLS reverse proxy (Caddy, Traefik, nginx) or a tunnel.
How the numbers work
Everything is an estimate, not lab-grade measurement.
| Piece | Formula |
|---|---|
| BMR | Mifflin-St Jeor: 10·kg + 6.25·cm − 5·age + 5 (male) / −161 (female) |
| Daily living | BMR × 1.2 (sedentary) |
| Steps | steps × kg × 0.0005 (≈0.04 kcal/step at 80 kg) |
| Workout | MET × 3.5 × kg ÷ 200 × minutes |
| Intake target | daily living + steps + workouts ± goal rate, with a 1,200/1,500 kcal floor |
Goal rate uses 7,700 kcal per kg: losing 0.5 kg/week subtracts 550 kcal/day. The "You" tab shows every component and lets you override the protein target (default 1.6 g/kg, or 1.8 g/kg when losing). Apple Health workouts use the calories Apple measured; step calories are always estimated with the formula above.
Food values come from whichever product or portion you log. Unpackaged food you cook yourself has to be added manually.
Apple Health
Browsers have no HealthKit access, so Counter gets Apple Health data three ways.
Import an export (history)
- iPhone: Health app → your profile → Export All Health Data → save and unzip it.
- Open Counter → You → Apple Health → pick a date range and
export.xml.
The file is parsed in the browser, so the multi-hundred-MB export never leaves the phone; only daily step totals and workout summaries are sent to the server. Steps are summed per day and workouts keep Apple's measured calories when present. Re-importing is safe: workouts are deduplicated by start time and each day's step total is replaced.
Push from a shortcut (daily)
Set INGEST_TOKEN in .env, restart, then have an iOS Shortcut read Health and post it:
curl -X POST http://HOST:31490/api/ingest/health \
-H "Authorization: Bearer $INGEST_TOKEN" \
-H "Content-Type: application/json" \
-d '{"steps": 8500, "workouts": [{"name": "Running", "minutes": 32, "kcal": 310, "met": 9}]}'
date defaults to today (add "date": "YYYY-MM-DD" to backfill) and workouts is optional. POST /api/ingest/steps still works for a steps-only shortcut. Without INGEST_TOKEN both return 403.
Automate with Health Auto Export (dynamic)
Health Auto Export is a commercial iOS app that reads HealthKit on the phone and POSTs JSON to an endpoint on a schedule. Counter understands its REST payload directly.
- In Health Auto Export, create an automation with type REST API.
- URL:
http://<server-ip>:31490/api/ingest/health-auto-export. - Add header
Authorization=Bearer <INGEST_TOKEN>(the token from.env). - Health metrics automation: select Step Count, turn Summarize Data on, group by Days, date range Today (or Previous 7 Days for a backfill), every 30–60 minutes.
- Workouts automation: data type Workouts, Export Version 2, date range Previous 7 Days, daily.
- Use Manual Upload once to backfill history.
Health Auto Export allows one data type per automation, which is why steps and workouts are separate. Each request replaces that day's step total and deduplicates workouts by the app's workout id, so repeats and retries are safe. iOS must be unlocked to read Health data and background runs can be delayed; the app's own docs call the frequency a desired cadence, not a guarantee.
If the phone cannot reach the server over plain HTTP, use HTTPS. /api/ingest/health remains available for anything that posts { "steps": …, "workouts": […] }.
Either push path raises that day's burn, and therefore the calories you can eat, by the imported activity. You can also type steps on the Today tab; the target always reflects whatever arrived most recently.
Bridges for steps and workouts
There is no Apple Health cloud REST API and no HealthKit access from a browser: the phone has to push the data. The practical options:
| Bridge | Runs on | Path into Counter | Notes |
|---|---|---|---|
| Apple Health export | iPhone | You → Apple Health picker | Built in. Manual, but complete history parsed on the phone. |
| Health Auto Export | iOS | /api/ingest/health-auto-export |
Built in. Scheduled background push, separate automations for metrics and workouts. Commercial app. |
| iOS Shortcuts | iOS | /api/ingest/health |
Free. Health actions inside Shortcuts, run from a personal automation; iOS decides when it fires. |
| HealthSave | iOS | its own /api/apple/batch contract |
Background sync and API key; Pro unlock. Needs an adapter, not implemented. |
| Health Data Export & AI Analyzer | iOS | REST/webhook with Bearer or Basic auth | Auto-sync with a compact preset payload; needs a mapping adapter. |
| Life Dashboard Companion | iOS | webhook / MQTT / Home Assistant | Paid, MIT-licensed; useful if you already run Home Assistant. |
| HC Webhook | Android | Health Connect → custom webhook | One-time purchase, 31 data types including steps and exercise sessions; needs a payload mapper. |
| Terra, Spike, Junction, Sahha, Rook | cloud | hosted webhook | Connect Apple Health, Health Connect and wearables for you, but entry pricing is hundreds per month and requires OAuth/SDK setup. |
| Open Wearables | self-hosted | MIT aggregator | Self-hosted alternative to the SaaS aggregators. |
Android note: Health Connect has no web API, and the Google Fit REST API is deprecated in 2026 (no new signups since May 2024). On Android, use a Health Connect exporter such as HC Webhook, or post to /api/ingest/health from Tasker or Home Assistant.
Configuration
| Variable | Default | Purpose |
|---|---|---|
APP_PORT |
31490 |
Host port published by Compose (picks a high, unlikely-to-collide number) |
PORT (deprecated) |
— | Use APP_PORT instead |
TZ |
UTC |
Used when a pushed step count has no date |
DATA_DIR |
./data (/data in Docker) |
SQLite database and WAL files |
INGEST_TOKEN |
unset | Enables the ingest endpoints (steps, health, health-auto-export) |
OFF_BASE_URL |
https://world.openfoodfacts.org |
Point at a mirror if needed |
OFF_TIMEOUT_MS |
8000 |
Open Food Facts request timeout |
The app has no login. It is built for a trusted home network — do not expose it to the internet without adding auth at the reverse proxy (and HTTPS, which also fixes the camera).
Development
npm install
npm run dev # http://localhost:31490, restarts on file changes
npm test # energy, planner and nutrition unit tests
Layout:
server/
index.js HTTP routes (day, entries, activities, plan, food, ingest)
db.js SQLite schema and profile helpers
energy.js BMR, steps, MET and daily target maths
nutrition.js Open Food Facts client + 30-day barcode cache
planner.js Meal plan selection
health-auto-export.js Health Auto Export payload adapter
seed.js Built-in meal library, MET presets, diet styles
public/ Single-page mobile frontend (no build step)
test/ node:test unit tests
The barcode cache is stored in SQLite, so a repeat scan works even if Open Food Facts is briefly unreachable.
Data sources
- Food and barcode data: Open Food Facts, available under the Open Database License. Product data is crowd-sourced and can be incomplete or wrong.
- Meal library and MET values are included in
server/seed.js; MET values follow the Compendium of Physical Activities.
Limits
- No native step sensor or direct Apple Health / Google Fit sync: HealthKit and Health Connect are on-device APIs, so use the export import, Health Auto Export, or a Shortcut.
- Imported step records are summed across sources, so a phone and a watch can slightly over-count a day.
- No accounts or multi-user support.
- No photo/visual food recognition — scanning is barcode-based.
- Nutrition estimates are only as good as the logged product data.