skip to content

// full-stack app

SleepTrack

A sleep journal with an analytics engine: an async FastAPI service and a Next.js and daisyUI app.

SleepTrack turns logged nights into a nightly score, trends, a chronotype estimate, the habits that help or hurt your sleep and a weekly report. Version 2 is a ground-up rewrite: an async FastAPI service on PostgreSQL and Redis with a background worker, and a Next.js 16 app typed from the API's OpenAPI schema, with a one-click demo and a mock API so the whole interface runs offline.

// moon05/22
year
2025
type
full-stack app
group
platforms and backends
tests
1,032 at 98% coverage

//in plain words

SleepTrack is a diary for your nights. Tap a timer at bedtime or log a night in seconds, tag it with habits like caffeine or exercise, and it works out a score, your natural rhythm, how steady your schedule is and which habits help or hurt, then emails you a weekly report. Every night is kept in your own time zone, and you can try it with a click, no sign-up.

for anyone curious why some nights are better, and engineers reading a full-stack reference

the problem

//01the problem

Logging sleep is the easy part. Making the log useful means knowing which night a session belongs to, which habits change your sleep and how steady your schedule really is, all in your own time zone and behind an account system you can trust with health data.

how it works

//02how it works

  1. 01

    Analytics that respect the clock

    Bedtimes are averaged as angles, so 23:30 and 00:30 average to midnight instead of noon, and every night belongs to the date it began in the user's time zone. The API computes a weighted score from duration, quality, latency, awakenings and bedtime, plus consistency, sleep debt, streaks, chronotype and social jet lag, cached per user in Redis and invalidated by a version number.

  2. 02

    Insights in plain language

    A rule engine behind a pluggable provider compares nights with and without each tag and ranks findings such as caffeine lowering your sleep quality. An ARQ worker emails weekly reports in each user's time zone, sends optional bedtime reminders and clears out demo accounts.

  3. 03

    Sessions built to be trusted

    Argon2id passwords, 15-minute access tokens and hashed refresh tokens that rotate on every use: reuse revokes the device, with a short grace window for two tabs refreshing at once. CSRF protection, Redis rate limits, device management, an audit log, email verification and optional Google sign-in with PKCE sit around it.

  4. 04

    Rules the database enforces

    PostgreSQL rejects overlapping nights with an exclusion constraint, allows one running timer per user through a partial unique index and searches notes with a trigram index. Every error leaves the API as an RFC 9457 problem document with a stable code.

  5. 05

    A client typed from the schema

    The Next.js app generates its types from the OpenAPI schema, keeps the access token in memory and refreshes it single-flight. A same-origin route handler streams /api to the service and forwards the client address, so rate limits see real users. It has two themes, a command menu with shortcuts for every page, a mobile dock, a year heatmap and charts with table views.

  6. 06

    Tested against the real thing

    Over a thousand backend tests run on real PostgreSQL and Redis, and Playwright drives sign-up with email confirmation, the journal, the timer and settings against the live API in CI. A mock API lets every page run offline, and a screenshot script visits every page in both themes and fails on any console error.

repositories

//03repositories

  1. 01

    The API and analytics engine

    sleep-track-backend

    An async FastAPI service on PostgreSQL and Redis with an ARQ worker for the weekly reports. Sessions rotate, passwords are hashed with Argon2id, every night is stored in the user's own time zone, and the analytics module turns logged nights into a score, trends, a chronotype estimate and habit correlations. 1,032 tests at 98% coverage.

    stars
    1
    language
    Python
    last push
    dec 1, 2026
  2. 02

    Next.js 16 and React 19 with daisyUI, typed end to end from the API's OpenAPI schema. A sleep timer, journal, analytics and insights, a command menu, light and dark themes, a one-click demo and a mock API so the whole interface runs with no backend. Playwright covers the flows.

    stars
    1
    language
    TypeScript
    last push
    nov 23, 2026

screens

//04screens

  1. The dashboard: Last night's arc against the goal, the sleep score, a timer to tap at bedtime, seven-night averages and the last thirty nights as bars.
    01The dashboardLast night's arc against the goal, the sleep score, a timer to tap at bedtime, seven-night averages and the last thirty nights as bars.
  2. Analytics: Nightly duration, score and quality over a chosen range, and when you sleep as bars from bedtime to wake time against your bedtime window.
    02AnalyticsNightly duration, score and quality over a chosen range, and when you sleep as bars from bedtime to wake time against your bedtime window.
  3. Insights: Patterns found in the nights, ranked by how much they matter: a tag that lowers quality, one that helps, a weekend shift, and tips.
    03InsightsPatterns found in the nights, ranked by how much they matter: a tag that lowers quality, one that helps, a weekend shift, and tips.
  4. The journal: Every logged night with its tags, mood and notes, editable in place.
    04The journalEvery logged night with its tags, mood and notes, editable in place.
  5. The weekly report: The same report the worker emails on Monday, rendered in the app.
    05The weekly reportThe same report the worker emails on Monday, rendered in the app.
  6. The command menu: Log a night, start the timer, export your data or jump anywhere, with the keyboard shortcuts shown beside each entry.
    06The command menuLog a night, start the timer, export your data or jump anywhere, with the keyboard shortcuts shown beside each entry.
  7. The landing page: What the app does and a one-click demo; this capture runs against the in-browser mock API, with no backend at all.
    07The landing pageWhat the app does and a one-click demo; this capture runs against the in-browser mock API, with no backend at all.

measured

//05measured

1,032
backend tests
run against real postgresql and redis in ci, 37 seconds
98%
test coverage
line and branch, measured on the api service; the floor is 85%
84
client unit tests
plus 16 playwright flows against the live api in ci
90
nights seeded by the demo
one click, no sign-up; the account deletes itself after a day

decisions

//06decisions

  1. 01

    chose SQLAlchemy 2 async with Alembic

    over the Tortoise ORM of version 1

    Repositories own queries and services own transactions, every relationship load is explicit because async forbids lazy loading, and the whole thing types under strict mypy. More verbose, and CI pays for it by running every migration up, check and down.

  2. 02

    chose a session denylist in Redis that fails open

    over checking the database on every request

    One Redis EXISTS per request keeps revocation immediate at almost no cost. If Redis is down, access tokens are honoured until they expire in fifteen minutes. The trade-off is written down in the decision record rather than hidden.

  3. 03

    chose a route handler proxy in the Next.js app

    over Next.js rewrites

    Rewrites do not add the forwarded client address, so the API would see one IP for every user and rate limits would break. The handler also reads the API address at runtime, so one image serves every environment.

  4. 04

    chose the overlap rule enforced twice

    over a check in the service alone

    The service gives a friendly error. The PostgreSQL exclusion constraint catches the race the service cannot see when two requests land at once.

  5. 05

    chose ARQ behind a queue protocol

    over Celery or a broker

    ARQ runs on the Redis already there, and an eager implementation runs jobs in-process for tests and single-container deployments. ARQ is in maintenance mode, which is accepted with the migration path contained to one adapter.

try it

//07try it

  1. //run the api, database, redis and mail catcher

    git clone https://github.com/KhaledSaeed18/sleep-track-backend.git && cd sleep-track-backend && docker compose up -d --build && make seed

    api docs at localhost:8000/api/v1/docs, mailpit at localhost:8025

  2. //run the web app against it

    git clone https://github.com/KhaledSaeed18/sleep-track-frontend.git && cd sleep-track-frontend && pnpm install && cp .env.example .env.local && pnpm dev

    node 24 and pnpm 12; or set next_public_api_mocking=true for no backend at all

  3. //run the backend suite

    make infra && make test

highlights

//08highlights

  • Weighted sleep score with circular bedtime statistics, chronotype and tag impact
  • Rotating refresh tokens with reuse detection and CSRF protection
  • Overlapping nights rejected by a Postgres exclusion constraint
  • Weekly email reports and bedtime reminders from a background worker
  • Client types generated from the API's OpenAPI schema; mock API for offline work
  • 1,032 backend tests at 98% coverage plus Playwright end-to-end tests in CI

built with

  • Python
  • FastAPI
  • SQLAlchemy
  • PostgreSQL
  • Redis
  • ARQ
  • TypeScript
  • Next.js
  • daisyUI
  • TanStack Query
  • Playwright
  • Docker

on githubsleep-track-backend

stars
1
license
MIT
language
Python
last push
dec 1, 2026

printings

//09printings

  1. First commits

    A FastAPI service on Tortoise ORM and a Create Next App client, started the same day.

  2. v2.0.0

    Both sides rewritten from the ground up: SQLAlchemy async, Alembic, Argon2id, rotating sessions, the analytics engine and worker on one side; Next.js 16, React 19, daisyUI 5, typed client, command menu and Playwright on the other.

questions

//10questions

Can I try it without signing up?
Yes. One click creates a throw-away account with about ninety nights of tagged history. A scheduled job deletes demo accounts after twenty-four hours.
How is the sleep score computed?
A weighted sum of duration against your goal, quality, latency, awakenings and bedtime adherence, each clamped between zero and one. Inputs you did not log drop out and the remaining weights renormalise. The full formulas are in the analytics document.
Why do 23:30 and 00:30 average to midnight?
Bedtimes are treated as angles on a 24-hour circle and averaged with circular statistics, so the wrap past midnight does not drag the average to noon.
What happens if two tabs refresh at once?
Within a ten-second grace window the second presentation of a rotated refresh token is simply rejected. Outside it, reuse is treated as theft: the device session is revoked and the account owner gets an email.
Can I run the interface without the backend?
Yes. One environment flag switches the app to a stateful mock API in the browser with seeded nights, so every page works offline.

related sheets

//11related sheets

//12contact

Say hello.I read everything.

Email is the fastest way to reach me. For anything that needs a conversation, book a call.

to

name
Khaled Saeed
country
Lebanon