Pantrie
A self-hosted pantry inventory and expiration tracker built with Node.js 20, Express, PostgreSQL 16, Redis 7, React 18, Docker Compose, and Caddy 2. It pairs mobile PWA barcode scanning and daily Web Push or SMTP alerts with CLI admin scripts and a native SwiftUI and SwiftData iOS companion.
Highlights
- Daily 8:00 AM node-cron expiration alerts via VAPID Web Push and SMTP email with per-user 3โ30 day windows
- Mobile PWA UPC-A/EAN-13 camera barcode scanning with Open Food Facts lookup and graceful manual fallback
- 5-service Docker Compose stack (PostgreSQL 16, Redis 7, Express API, FROM scratch Vite bundle, Caddy 2 auto-TLS)
- CLI-driven admin user creation, password recovery, and VAPID key generation via docker exec without public signup
- Phase 2 native SwiftUI / SwiftData / CloudKit iOS companion with local notifications and storage-location tags
Links
Pantrie: Building a Self-Hosted Pantry & Expiration Tracker
Project Details
- Status: Public / Open Source (
v1.0.0, MIT License)- Launch Date: January 20, 2026 (v1.0.0 Self-Hosted Web Stack) ยท July 20, 2026 (Native iOS SwiftUI/SwiftData Companion Milestone)
- Repository: github.com/ryanrclewis/pantrie (opens in a new tab)
- Documentation: Full Technical Docs (README.md) (opens in a new tab) ยท Setup & Operations Guide (SETUP.md) (opens in a new tab)
- Release Notes & History: GitHub Releases (opens in a new tab) ยท Commit History (opens in a new tab)
- Tech Stack: Node.js 20, Express, PostgreSQL 16, Redis 7, React 18, Vite, TanStack Table, Docker Compose, Caddy 2, PWA Web Push (plus a SwiftUI / SwiftData / CloudKit iOS client)
1. The Problem: Household Food Waste & Inventory Friction
My parents have a large pantry, and keeping track of what is actually sitting in it has always been a bit of a losing battle. Once cans, sauces, snacks, and bulk staples get pushed toward the back of deep shelves, expiration dates are easy to forget, and food ends up going to waste.
When you look closely at why that keeps happening, a few practical patterns stand out:
- Out of sight, out of mind: Expiration dates are printed in tiny type on random corners of packaging, and nobody remembers them a week after unpacking groceries.
- Duplicate grocery runs: Standing in a supermarket aisle, it is hard to remember whether there is already an unopened jar of marinara at home, so you buy another one while the older jar quietly expires in the back.
- High entry friction: Plenty of people try tracking pantry items in a shared spreadsheet or notes app, and that makes sense on paper. In practice, typing out product names, brands, and dates for twenty items while putting away groceries gets tedious fast, and the habit usually dies within a week.
- Subscription fatigue: There are commercial pantry apps on the app stores, and a few of them are pretty well designed. Still, many lock basic reminders behind monthly subscriptions, crowd the screen with ads, or keep everyday household data sitting on third-party servers that could change pricing or shut down later.
I wanted to build something my parents would actually stick with: a quiet, low-friction tool where scanning a barcode takes a few seconds, leftovers can be typed in quickly, and upcoming expirations show up before food spoils.
2. Who Uses It & Why Self-Hosted Docker + CLI
Two Different Users Under One Roof
Building software for a family means designing for two very different day-to-day contexts, even inside the same house:
| User Role | Who | Where They Use It | What Matters Most |
|---|---|---|---|
| Primary User (Household Member) | Mom & Dad in the kitchen or grocery store | Mobile browser (PWA) while unpacking groceries or planning dinner | Fast camera barcode scanning, quick manual entry for produce and leftovers, a scannable expiration table, and passive morning reminders |
| Operator / Admin | Dad (homelab maintainer) | SSH terminal and the Admin Dashboard on his home server | Reproducible Docker Compose setup, automatic HTTPS, no random internet signups, straightforward database backups, and easy password resets |
Why a Self-Hosted Docker & CLI Approach?
My dad already runs a homelab at home, so building Pantrie as a self-hosted Docker stack with CLI admin tooling ended up solving several headaches at once.
First up, running it on hardware that is already humming in the house means zero recurring SaaS fees and full control over the data. Backups are just standard PostgreSQL dumps on a schedule he already trusts.
Second, mobile browser security shaped the deployment model early on. For anyone who hasn't wrestled with browser camera APIs before, phones block getUserMedia (which the barcode scanner needs) unless the page is served over HTTPS. Bundling Caddy 2 directly into docker-compose.yml handles Let's Encrypt TLS certificates automatically once a domain points to the server. That took away what is usually the most annoying step of self-hosting a camera-enabled web app.
Third, most web applications include a public /register page out of the box, which makes total sense for open SaaS tools. On a personal family server exposed to the public internet, though, open registration mostly invites spam accounts and extra attack surface. Leaving self-registration out and handling the first admin account (npm run admin:create-user) and lockout recovery (npm run admin:reset-password) through docker exec CLI commands keeps user provisioning tied to host shell access or an existing admin session. It also matches the way homelab operators already manage their services.
Finally, packaging PostgreSQL, Redis, the Node.js API, the React frontend build, and Caddy into one docker-compose.yml makes upgrades and server moves predictable. Pulling updates or rebuilding the stack comes down to a couple of familiar commands.
3. System Architecture
flowchart LR
subgraph Client["Household Clients (Mobile PWA / Desktop)"]
Browser["React 18 SPA + Service Worker\n(html5-qrcode and Web Push)"]
end
subgraph Edge["Edge & Static Serving (pantrie-network)"]
Caddy["pantrie-caddy (Caddy 2)\nAuto TLS, HTTP/3, Security Headers"]
DistVol[("frontend-dist\nDocker Volume")]
FEBuild["pantrie-frontend\n(node:20-alpine to scratch)"]
end
subgraph Core["Application & Scheduling"]
API["pantrie-backend (Node.js 20 / Express)\nREST API, Passport JWT, Joi, node-cron (08:00)"]
CLI["Admin CLI Scripts\n(docker exec -it pantrie-backend)"]
end
subgraph Data["Persistence & External Services"]
PG[("pantrie-postgres\nPostgreSQL 16 + postgres-data")]
Redis[("pantrie-redis\nRedis 7 AOF + redis-data")]
OFF["Open Food Facts API\n(Product Metadata Lookup)"]
Notify["Web Push (VAPID) and\nSMTP Email Server"]
end
Browser -- "HTTPS (443 / QUIC)" --> Caddy
FEBuild -. "Publishes /dist" .-> DistVol
Caddy -- "Static SPA Files" --> DistVol
Caddy -- "/api/* and /health" --> API
CLI -- "Direct DB Transactions" --> PG
API -- "Parameterized SQL" --> PG
API -. "Configured Cache/Session URL" .-> Redis
API -- "5s Timeout Lookup" --> OFF
API -- "Daily 8:00 AM Digest" --> Notify4. Key Features
Expiration Alerts & Notifications
- Daily Scheduled Check: A
node-cronjob runs every morning at8:00 AM(0 8 * * *), comparing each user's inventory against their chosen lead time. - Per-User Alert Windows: Everyone in the household can pick whether they want a heads-up 3, 7, 14, or 30 days before items expire (
user_preferences.alert_threshold_days). - Multi-Channel Delivery: Alerts can go out as Browser Push Notifications (VAPID-signed
web-pushhandled by the PWA Service Worker), HTML Emails (throughnodemailerand any SMTP relay), or Both. - Automatic Cleanup of Stale Subscriptions: When sending push alerts across multiple devices, the backend runs
Promise.allSettledand deletes dead endpoints frompush_subscriptionswhenever a push service replies with HTTP410 Gone. - At-a-Glance Inventory Triage: The main inventory table sorts by soonest expiration by default and labels every row with color-coded badges (
Expired,Expires Today, warning days left, or fresh).
Barcode Scanning & Relational Item Schema
- Grocery-Focused Camera Scanner: The frontend uses
html5-qrcodeaimed at the rear camera (facingMode: 'environment') at10 FPS, narrowed specifically to UPC-A and EAN-13 barcodes so the camera does not misfire on promotional QR codes printed on boxes. - Open Food Facts Lookup with Graceful Fallback: For those who haven't come across it, Open Food Facts is an open, community-maintained database of grocery products. Pantrie proxies lookups through
GET /api/food-items/barcode/:barcodewith a 5-second timeout. If a product is missing, or if you are logging fresh produce and leftovers, the form keeps the scanned barcode (when present) and drops right into manual entry (is_manual_entry: true). - User-Scoped Relational Schema: PostgreSQL stores everything across four clean tables:
users(id,username,email,password_hash,is_admin,created_at)user_preferences(user_idFK,alert_threshold_days,notification_method)food_items(id,user_idFK,barcodenullable,product_name,brand,expiration_date,quantity,notes,is_manual_entry,created_at,updated_at)push_subscriptions(id,user_idFK,endpoint,p256dh_key,auth_key)
- Server-Side Date Math: Item queries calculate
EXTRACT(DAY FROM (expiration_date - CURRENT_DATE)) AS days_until_expirationdirectly in PostgreSQL so expiration counts stay consistent regardless of a phone's local clock.
CLI Commands
Account bootstrapping, cryptographic key setup, and recovery all live as interactive Node.js scripts inside the backend container:
npm run admin:create-user(backend/src/scripts/createAdmin.js): Prompts for username, email, password, and admin status, hashes the password with bcrypt, and inserts the user plus default preferences inside a single PostgreSQL transaction.npm run admin:reset-password(backend/src/scripts/resetPassword.js): Looks up an account by username or email, checks the 6-character minimum length, and updates the password hash directly for quick lockout recovery.npm run generate-vapid(backend/src/scripts/generateVapid.js): Generates Web Push VAPID keys and prints them as copy-ready.envlines (WEB_PUSH_PUBLIC_KEY,WEB_PUSH_PRIVATE_KEY,VITE_VAPID_PUBLIC_KEY).- Day-to-Day Ops: Paired with standard
docker-composelifecycle commands and one-linepg_dump/psqlbackup and restore workflows.
Container Architecture
- Five Services on an Isolated Network:
pantrie-postgres,pantrie-redis,pantrie-backend,pantrie-frontend, andpantrie-caddytalk over a dedicatedpantrie-networkbridge. - Healthcheck-Gated Startup:
pantrie-backendwaits until both PostgreSQL (pg_isready) and Redis (redis-cli ping) report healthy before booting, and exposes its own/healthendpoint checked every 30 seconds. - Static-Only Frontend Image:
pantrie-frontendbuilds the Vite bundle insidenode:20-alpine, copies/app/distinto aFROM scratchimage, and shares it with Caddy through thefrontend-distvolume. That avoids running a separate Nginx or Node server just to serve static assets. - Edge Hardening via Caddy: Caddy handles automatic HTTPS (including HTTP/3 QUIC on UDP 443), compresses responses with
gzipandzstd, writes JSON access logs, removes theServerheader, and setsX-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy, and a Content Security Policy allowlistingworld.openfoodfacts.org.
Persistence Layer
- Named Volumes for Clean Upgrades: Five Docker volumes keep persistent state separate from container rebuilds:
postgres-datafor the relational database,redis-datafor Redis 7 with Append-Only File persistence (--appendonly yes),frontend-distfor built assets, andcaddy-data/caddy-configfor ACME certificates and proxy state. - Automated Backups: Set up to work cleanly with a nightly host cron job (
0 2 * * * docker exec pantrie-postgres pg_dump ... | gzip) and plain SQL restores. - Phase 2 Native iOS Expansion: Since then, in July 2026, I added a native SwiftUI companion app (
Pantrie/) backed by SwiftData and CloudKit sync, localUNUserNotificationCenteralerts, storage location tags (Pantry,Fridge,Freezer), and automatic food category inference from Open Food Facts v2.
5. Engineering Decisions & Trade-Offs
To dig into how the system was actually built, here is a summary of the main technical choices and why I landed on them.
| Area | What I Chose | Why It Made Sense Here |
|---|---|---|
| Language & Runtime | Node.js 20 (native ESM) + Express, React 18 + Vite | Sharing JavaScript across the API, PWA frontend, and admin CLI scripts kept context-switching low while giving access to mature packages (pg, web-push, node-cron, html5-qrcode). |
| Database | PostgreSQL 16 with parameterized SQL via pg.Pool | Foreign keys, ACID transactions, native date arithmetic, and reliable pg_dump backups beat out SQLite once multi-user isolation and concurrent web plus cron jobs were in the picture. |
| Auth & Access Control | Stateless Passport JWT + bcrypt (10 rounds) + admin-only user creation | Keeps mobile PWA auth simple without sticky sessions; every item query filters by user_id to prevent cross-user access; helmet and express-rate-limit (100 req / 15 min) protect /api/. |
| Docker & Compose | Alpine images, non-root nodejs user (UID 1001), FROM scratch frontend | Keeps images lean, avoids running the API as root, and lets Caddy pull double duty as TLS terminator and static file host. |
| Error Handling | Centralized Express error middleware + PostgreSQL SQLSTATE mapping | Turns database errors (23505 to 409 Conflict, 23503 to 400 Bad Request) into consistent JSON responses while hiding raw stack details in production. |
| Testing & Verification | Joi boundary validation, container healthchecks, and a manual setup checklist | Got a working v1 into my parents' kitchen quickly, with a clear plan for adding automated unit, integration, and CI tests next. |
Language & Full-Stack Coherence
For a solo self-hosted project, keeping the API, operational CLI scripts, Service Worker, and React UI in one language saved a lot of friction. Express stays out of the way and keeps routes easy to read, while Vite and TanStack Table give the inventory page a quick, spreadsheet-like feel (search, column sorting, filtering) without pulling in a heavy UI suite.
Meanwhile, building the Phase 2 SwiftUI client showed where native platforms still shine over web apps: camera launch is snappier, SwiftData works offline naturally, and iOS local notifications do not need an SMTP server or VAPID key management.
Database & Query Safety
ORMs like Prisma or Sequelize are popular in Node projects, and they are pretty good when you are juggling dozens of tables and complex migrations. For a four-table schema, though, adding an ORM felt like extra abstraction I did not need. Writing raw parameterized SQL ($1, $2, ...) directly with pg.Pool protects against SQL injection, keeps every query transparent when debugging, and makes PostgreSQL features like EXTRACT(DAY FROM ...) trivial to use.
Every food_items read, update, and delete includes WHERE id = $1 AND user_id = $2 so one household member cannot accidentally or intentionally touch another user's records by guessing an integer ID. On top of that, creating a user (in both POST /api/admin/users and createAdmin.js) wraps the users insert and the default user_preferences insert in an explicit BEGIN / COMMIT transaction with ROLLBACK and client.release() in a finally block. That way, an account never lands in the database half-configured.
One honest architectural note: redis:7-alpine with AOF persistence is wired into docker-compose.yml (REDIS_URL) to support future Open Food Facts barcode caching and JWT revocation, while v1 runs authentication statelessly via Passport JWT to stay simple.
Dockerfile & Compose Design
A few small container hygiene choices make a big difference in a homelab stack:
backend/Dockerfileinstalls production packages only (npm ci --only=production), creates an unprivilegednodejsuser (UID/GID 1001), updates ownership on/app, and switches off root withUSER nodejs.frontend/Dockerfilecompiles the Vite bundle using build-timeARG VITE_API_URL, then drops everything except/app/distintoFROM scratch. Mounted intopantrie-caddyvia the sharedfrontend-distvolume, the frontend uses practically no runtime memory.docker-compose.ymlgates backend startup oncondition: service_healthyfor Postgres and Redis so the API does not crash-loop during first boot. Insidebackend/src/index.js,SIGTERMandSIGINThandlers let the server exit cleanly duringdocker-compose down.- Separate
.dockerignorefiles inbackend/andfrontend/keepnode_modules/,.env*secrets, logs, anddist/out of the Docker build context.
Error Handling & External Dependencies
At the API edge, backend/src/middleware/validation.js validates payloads with Joi using { abortEarly: false }, returning all field errors together in one 400 response instead of making the user fix one field at a time. Downstream, backend/src/middleware/errorHandler.js maps PostgreSQL constraint errors (23505 for unique conflicts, 23503 for missing foreign keys) to clean HTTP status codes and strips raw error messages whenever NODE_ENV is not development.
External APIs are where kitchen apps usually break down, so barcode lookup was written to fail softly. Open Food Facts is a community database and can be slow or missing local store brands. The backend caps requests at 5000 ms and returns { found: false } on timeouts or misses instead of throwing a 500. In AddItemPage.jsx, that automatically preserves the scanned barcode and opens the manual entry fields so unpacking groceries never stalls.
Notification delivery follows the same mindset. If SMTP credentials or VAPID keys are left blank in .env, notificationService.js logs a warning and skips that channel rather than crashing the daily cron job. Multi-device Web Push delivery uses Promise.allSettled so one expired browser subscription never blocks alerts to another phone.
CLI Ergonomics & Developer Experience
I skipped heavy CLI frameworks and built the admin scripts directly on Node's built-in readline module. They stay small, have zero extra dependencies, and focus on clear prompts: sensible defaults (Is Admin? (yes/no) [yes]), plain validation messages, proper exit codes (0 vs 1), and readable โ confirmation summaries. npm run generate-vapid prints exact .env assignments so setup is a straight copy-and-paste.
On the documentation side, I split the docs into two pieces on purpose: README.md (opens in a new tab) as the full technical reference (endpoints, schema, security, backups) and SETUP.md (opens in a new tab) as a step-by-step deployment and troubleshooting guide alongside .env.example.
Testing & Verification
For the initial homelab release, I leaned on runtime guardrails and structured manual checks rather than building out an automated test suite upfront. Specifically, v1 relies on Joi request validation, PostgreSQL foreign-key and unique constraints, Docker healthchecks across Postgres, Redis, and the API, and a 9-step verification checklist in SETUP.md covering container health, migrations, admin login, user creation, barcode and manual item entry, and notification settings.
Being upfront about that trade-off matters: there are no automated unit or integration tests in the repository yet. Before pushing Pantrie toward wider community use, the next step is putting a straightforward test setup in place:
- Unit tests (Vitest or Node's built-in test runner): Covering expiration-day boundary math (
days < 0,days === 0, threshold edges), alert text formatting, and Joi schema validation. - API integration tests (Supertest + ephemeral PostgreSQL via Testcontainers): Verifying JWT auth, cross-user isolation (
404/403), transaction rollbacks on duplicate emails (409), and mocked Open Food Facts timeouts. - GitHub Actions CI: Running
docker-compose configchecks, container build checks, and clean schema migration smoke tests on every commit.
6. Usage Examples & Walkthrough
Bootstrapping & Starting the Stack
$ cp .env.example .env
$ cd backend && npm install && npm run generate-vapid=== Generate VAPID Keys for Web Push ===
Add these to your .env file:
WEB_PUSH_PUBLIC_KEY=BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U
WEB_PUSH_PRIVATE_KEY=UUxI4O8-FbRouAevSmBQ6o18hgE4nSG3qwvJTfKc-ls
Also add this to your frontend environment:
VITE_VAPID_PUBLIC_KEY=BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U$ docker-compose up -d
$ docker-compose psNAME IMAGE STATUS PORTS
pantrie-backend pantrie-backend Up 2 minutes (healthy) 0.0.0.0:3000->3000/tcp
pantrie-caddy caddy:2-alpine Up 2 minutes 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:443->443/udp
pantrie-frontend pantrie-frontend Exited (0) (static bundle published to frontend-dist)
pantrie-postgres postgres:16-alpine Up 2 minutes (healthy) 0.0.0.0:5432->5432/tcp
pantrie-redis redis:7-alpine Up 2 minutes (healthy) 0.0.0.0:6379->6379/tcpCreating the First Admin & Resetting Passwords via CLI
$ docker exec -it pantrie-backend npm run admin:create-user=== Create Admin User ===
Username: dad
Email: dad@homelab.local
Password: ********
Is Admin? (yes/no) [yes]: yes
โ User created successfully:
ID: 1
Username: dad
Email: dad@homelab.local
Admin: true$ docker exec -it pantrie-backend npm run admin:reset-password=== Reset User Password ===
Username or Email: mom@homelab.local
Found user: mom (mom@homelab.local)
New Password: ********
โ Password reset successfully
User: momREST API Example (Login, Barcode Lookup & Adding an Item)
# 1. Authenticate and grab a Bearer JWT
TOKEN=$(curl -s -X POST https://pantrie.example.com/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"mom","password":"your-password"}' | jq -r '.token')
# 2. Look up a scanned UPC-A barcode through the Open Food Facts proxy
curl -s https://pantrie.example.com/api/food-items/barcode/0041196910759 \
-H "Authorization: Bearer $TOKEN" | jq{
"found": true,
"product": {
"barcode": "0041196910759",
"product_name": "Organic Vegetable Broth",
"brand": "Pacific Foods",
"image_url": "https://images.openfoodfacts.org/images/products/..."
}
}# 3. Save the item with an expiration date
curl -s -X POST https://pantrie.example.com/api/food-items \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"barcode": "0041196910759",
"product_name": "Organic Vegetable Broth",
"brand": "Pacific Foods",
"expiration_date": "2026-02-01",
"quantity": 2,
"notes": "Bottom pantry shelf"
}' | jqInventory Web UI Preview (TanStack Table)
Note for portfolio publishing: Swap in or pair this layout preview with live screenshots from your running instance (
/,/addcamera scanner, and/admin).
+--------------------------------------------------------------------------------------+
| Pantrie [Inventory] Add Item Settings Admin dad [Admin] [Logout] |
+--------------------------------------------------------------------------------------+
| Food Inventory [+ Add Item] |
| |
| [ Search items... ] |
| |
| PRODUCT NAME | BRAND | EXPIRATION DATE | QTY | STATUS |
| -------------------------+----------------+-----------------+-----+----------------- |
| Whole Milk | Organic Valley | Jan 19, 2026 | 1 | [ Expired ] |
| Greek Yogurt | Fage | Jan 20, 2026 | 2 | [ Expires Today ]|
| Organic Vegetable Broth | Pacific Foods | Jan 25, 2026 | 2 | [ 5 days left ] |
| Homemade Marinara | - | Jan 27, 2026 | 1 | [ 7 days left ] |
| Manual entry | | | | |
| Chickpeas (Canned) | Goya | Nov 14, 2026 | 4 | [ 298 days left ]|
| |
| Showing 5 of 5 items |
+--------------------------------------------------------------------------------------+7. What I Learned & What's Next
Two lessons stuck with me while putting Pantrie together. First, browser security rules can quietly dictate your whole infrastructure. Realizing early on that phones block camera scanning without HTTPS turned automatic TLS with Caddy from a nice bonus into a core piece of the architecture. Second, designing the fallback path matters just as much as the happy path. No barcode database covers local bakery bread, farmers' market produce, or last night's soup, so making manual entry feel quick and natural kept the app usable in a real kitchen.
Going forward, there are a few clear pieces I want to clean up and build next:
- Commit the SQL migration file (
backend/migrations/01_init.sql) and wire upnpm run migrateso anyone cloning the repo gets a clean database setup out of the box. - Put the provisioned Redis container to work caching
/api/food-items/barcode/:barcoderesponses to cut repeat lookup latency and avoid leaning too hard on Open Food Facts. - Add shared household inventories so both of my parents can view and edit one shared pantry while keeping their own alert preferences, alongside automated Vitest and Supertest checks in CI.