Skip to content
Lucas B. Jolibois

TerapiMatch · Therapy marketplace

Live726 commits in four months

Three products,one codebase.

TerapiMatch lets people in Denmark meet a therapist on video before they book. I designed and built it: the marketplace clients search, the practice therapists run on, and the payment rail between them.

4
months, first commit to live
183
database migrations
101
Postgres functions
7
jobs on a schedule
(The build)

Four months, 726 commits.Four months,726 commits.

From an empty repo on 16 June to the marketplace it is today. Every bar is a day of my commits; the words are what those commits say they did.

Day

001 / 130

Date

16 Jun

Commits

11

Lines added

2,329

16 Jun

Day one.

An empty repo becomes a Next.js app with Supabase auth, sign-up by emailed code, and a proxy that refreshes every session.

  • app/(auth)/actions.ts+286
  • app/(auth)/auth-flow.tsx+171
git log --author=lucas --since=2026-06-16 --oneline
  1. e905e78feat: add Supabase SSR clients and session-refresh proxy
  2. 666decffeat(auth): email/password auth with email-code verification and route protection
  3. 3b156c8feat(auth): password reset, getClaims-based DAL, and httpOnly email cookies

01 / 13

Drag the strip to go to any day

16 JunJulAugSepOct

(The brief)

docs / terapimatch-platform.mdLive

A marketplace that runs the whole session, from first look to payout.

Owner
Lucas
Client
TerapiMatch
Built
16 Jun – now

Context

A Danish marketplace for therapy. Clients choose a therapist by video and by fit, book online or in the clinic and pay as they book; therapists run their practice on it, from their site to their payouts.

Constraints

  • Real moneyheld until the session, then paid out
  • Health datanever sent to analytics
  • Three calendarsGoogle, Outlook and iCloud, read live
  • Four monthsfrom an empty repo to a live marketplace

Goals

Non-goals

A directory with a contact formFloats anywhere near moneyPaying out before the session

ScopeProductUX & UIFrontendBackendPostgresPaymentsCalendarsEmailInfra

(The product) · live site

Six real pages, from a search to a session.

  1. 01 Meet them first
  2. 02 Search by fit
  3. 03 Or let it match you
  4. 04 Watch, then book
  5. 05 Start from what you feel
  6. 06 The other side

01

Meet them first

terapimatch.dk

The front page leads with faces, not forms. Profile videos play in the hero, and the search for place, specialty and format sits right under them.

How it's built

The collage is curated in the admin; the search hands over to the directory with its filters in the URL.

Next.jsMotionVimeo

terapimatch.dk
terapimatch.dk on desktop
terapimatch.dk on a phone

02

Search by fit

terapimatch.dk/terapeuter

Place, specialty, format, price, gender and education, as video cards or on a map. Results rank by how many of your filters each therapist meets, so the list never comes back empty.

How it's built

Distances come from each clinic's coordinates, and the map clusters its pins with MapLibre.

PostgresMapLibre

terapimatch.dk/terapeuter
terapimatch.dk/terapeuter on desktop
terapimatch.dk/terapeuter on a phone

03

Or let it match you

terapimatch.dk/match

Five questions, from what you want help with to how far you would travel, and a ranked shortlist with the reasons behind every percentage.

How it's built

One pure scoring function, shared by the server, the tests and the admins' matching studio.

TypeScriptPostgres

terapimatch.dk/match
terapimatch.dk/match on desktop
terapimatch.dk/match on a phone

04

Watch, then book

janni-gregersen.terapimatch.dk

Every therapist's page is a site of their own, on their own subdomain: their video, their approach, their prices, and a calendar with the hours they actually have.

How it's built

Four templates, one renderer; the calendar reads their Google, Outlook or iCloud before it offers a time.

Wildcard DNSCalDAVGraph

janni-gregersen.terapimatch.dk
janni-gregersen.terapimatch.dk on desktop
janni-gregersen.terapimatch.dk on a phone

05

Start from what you feel

terapimatch.dk/specialer/angst

Each specialty has a page in plain Danish: the typical signs as a list you can tick, what helps, and the therapists who work with it.

How it's built

The carousel and the quotes are the published directory, filtered by that specialty. Ticking signs never scores or diagnoses.

Next.jsSEO

terapimatch.dk/specialer/angst
terapimatch.dk/specialer/angst on desktop
terapimatch.dk/specialer/angst on a phone

06

The other side

terapimatch.dk/for-terapeuter

The page that signs therapists up: what they get, what it costs and how the money moves, in claims that match the code behind them.

How it's built

Signing up leads into onboarding and an admin review; a therapist goes live only once approved.

SupabaseResend

terapimatch.dk/for-terapeuter
terapimatch.dk/for-terapeuter on desktop
terapimatch.dk/for-terapeuter on a phone
(Live components)components/landing/home

Every section is a small machine.Every sectionis a small machine.

Three rooms of that front page, copied from the repo and running here. Open a tab and use it; the pane underneath x-rays it while it runs.

terapimatch.dk/#terapeuter

Mærk kemien

Mød din næste terapeut

Læs om terapeutens tilgang og se terapeutens korte profilvideo. Mærk mavefornemmelsen gennem skærmen, så du er tryg ved dit valg, inden du booker.

Se alle terapeuter
Profilvideo01/23
Swipe for at skifte terapeut.

Dzevada Sejdic

Metakognitiv Terapeut

“Du er ikke dine tanker. You are not your thoughts. Ti nisi svoje misli.”

StressAngstDepression
Onlinefra 495 kr
X-raycomponents/landing/home/therapist-reel.tsx · 385 lines

The videos are the product, so the front page plays them.

  1. 01Muted previews run 16 seconds, then hand over to the next face. Unmute, swipe or pick someone and the clip plays to the end.
  2. 02The room takes its light from the video: every 150 ms the playing frame is drawn into a 32 × 18 canvas and blurred 90 px behind the stage.
  3. 03Nothing reads those pixels back, so the cross-origin video never needs CORS.

The light in the room

waiting for a video

drawImage → 32 × 18 = 576 px
blur(90px) · opacity 0.3
(The system)Five lines, sixteen stations

Every journey, one map.Every journey,one map.

Finding someone, booking them, their calendars and the money all run through one codebase. Here it is the way a city draws its trains: each line a journey, each station a real part of the code.

Directory/terapeuterMatchutils/match/score.tsTheir profile/terapeut/[slug]their-name.terapimatch.dkproxy.tsSlotsgenerateSchedule()Holdhold_appointment()Checkoutcard only, on purposeWebhookpayments-webhookBookedpromote_appointment()EmailsResend · .icsBusy timegetBusy() × 3Google · Outlook · iCloudpush · Graph · CalDAVEvents writtencreateEvent()Escrowtransfer_groupSettlementhourly, :30PayoutStripe ConnectInvoicethe 1st · gapless

Find · From a search to the right person

Directory/terapeuter

Filter by speciale, format, price and distance, on a MapLibre map. Online mode turns the page blue.

(One booking)

Twelve seconds, eight days.Twelve seconds,eight days.

One trip across that map, as the systems see it. One client books one session on a therapist's own site: held, paid, booked once, put in three calendars, reminded, paid out and invoiced. The therapist is made up; every system and function is real.

Every system it touches

click1 min1 h1 day8 days

Time on a stretched scale: the first twelve seconds take up most of it.

Chapter 01Marketplace

A score that explains itself.A score thatexplains itself.

The problem

Most people don't know what kind of therapist they need, and a wall of profiles doesn't tell them.

The call

Five questions and one pure scoring function: the same code runs on the server, in a unit test and in the admins' live preview.

The result

A ranked shortlist where every percentage comes with its reasons, and a skipped question counts against no one.

terapimatch.dk/match4 of the 5 questions

01Hvad ønsker du hjælp til?

3 valgt

02Foretrækker du en terapeut af et bestemt køn?

03Online eller fysiske sessioner?

05Hvor bor du, og hvor langt vil du køre?

ingen grænse

The live form's questions, minus age. Topics and gender score with the weights they were seeded with; format and distance only gate.

Ranked by the engine

raw fit · shown on a private display band

  1. AngstStressTankemylderSøvnproblemer

    Specialer3 of 3 → 3 + 1.00 × (15 − 3)15.0 / 15

    KønLigegyldigt: full, for everyone4.0 / 4

    Fitearned ÷ possible19.0 / 19 = 100%

A question you skip can't count against anyone.

No answer scores the dimension's neutral for everyone, or drops it out of both the points earned and the points possible.

The breakdown is the score.

Each line carries earned and max, so the percentage and its reasons are the same arithmetic.

Gates never dead-end.

Format and distance filter; if that leaves nobody, everyone is scored and flagged. Ties go by id, so a refresh never reshuffles.

utils/match/score.ts
1case "set_overlap": {2  const want = [...new Set(asArray(client).map(norm))]3  const has = new Set(asArray(therapist).map(norm))4  if (!want.length) return null // out of BOTH sums5  const ratio = want.filter((w) => has.has(w)).length / want.length6  // Soft curve: a partial overlap still scores well,7  // and a total miss lands on minBonus rather than zero.8  const earned = dim.minBonus + ratio * (dim.weight - dim.minBonus)9  return { earned, matched: ratio >= 0.5 }10}
Chapter 02Booking engine

One hour, one client.One hour,one client.

The problem

Two people can reach for the same hour at once, a therapist needs a break between clients, and a slot has to wait while someone pays.

The call

Let Postgres referee: an exclusion constraint on time ranges, a per-therapist lock for the buffers, and holds that last exactly 15 minutes.

The result

A double booking can't be written, however the requests race, and a slot left at checkout frees itself.

Thursday 29 OctoberEurope/Copenhagen · 50 min sessions

buffer_minutes
offered slots
08:0009:0010:0011:0012:0013:0014:0015:0016:0017:0018:00Tandlæge · Google
Booked09:00–09:50
Held · paying9:40 left
10:00–10:50
← drag →

tstzrange('2026-10-29 10:00+01', '2026-10-29 10:50+01', '[)')

Free. It can be held.

Every check passes: their calendars, the buffered overlap under the lock, and the constraint.

Two clients want Thursday 10:00, one millisecond apart

pg_advisory_xact_lock serialises them per therapist, so the second one sees the first one's hold.

Client A
—idle
Client B
—idle
supabase/migrations/…_appointment_hold_guard.sql
1-- The hard invariant: two live rows for one therapist2-- can never overlap, whatever the code above does.3alter table public.appointments4  add constraint appointments_no_overlap5  exclude using gist (6    therapist_id with =,7    tstzrange(starts_at, ends_at, '[)') with &&8  ) where (status in ('booked', 'held'));
hold_appointment()
1perform pg_advisory_xact_lock(hashtext(p_therapist_id::text));2perform public.expire_stale_holds(p_therapist_id);3if exists (select 1 from public.appointments a4  where (a.status = 'booked' or a.held_until > now())5  and tstzrange(a.starts_at - make_interval(mins => v_buffer),6                a.ends_at + make_interval(mins => v_buffer), '[)')7      && tstzrange(p_starts_at, p_ends_at, '[)')8) then raise exception 'slot unavailable' using errcode = '23P01';

The buffer can't live in the constraint, so the function checks it under a per-therapist lock. A hold lasts 15 minutes, and one therapist can have at most 12 at once, so a script can't lock up a calendar.

Chapter 03Calendar sync

Busy anywhere, unbookable here.Busy anywhere,unbookable here.

The problem

Therapists already live in Google, Outlook or iCloud, often all three. A booking page that doesn't know about the dentist double-books them.

The call

Read all three at once whenever slots are built, write every booking back into each, and touch only the events TerapiMatch created.

The result

Their page only ever offers time they actually have, and if a calendar can't be read, a booking fails closed instead of guessing.

Their calendars · click an hour

Google Calendar● connected
Supervision
Outlook● connected
iCloud● connected
Hente Alma

Their booking page · what a client sees

maja-holm.terapimatch.dk

Book din samtale online.

Torsdag 29. okt.1 til 1 terapi · 50 min

Read through a 30-second cache that every booking change clears. A hold always reads their calendars again, strictly.

Chapter 04Payments & ledger

Paid out to the øre.Paid outto the øre.

The problem

Clients pay when they book; therapists should be paid only for sessions that happened, at a commission that depends on how the client found them.

The call

Hold the money on the platform, settle each session after it ends, and let one pure function of integer øre decide every split.

The result

No øre lost to rounding, no transfer made twice, a clip paid or returned but never both, and invoices with no gaps.

terapimatch.dk/dashboard/oekonomi

Mon 5 OctNothing booked yet, so nothing earned. This is the page a new therapist starts from.

Økonomi

Klar til udbetalinger

Til rådighed

0 kr

Klar til næste udbetaling

På vej

0 kr

Afholdt · afventer i Stripe

Kommende

0 kr

Endnu ikke afholdt

Tjent i alt

0 kr

Din andel, samlet

Udbetales ugentligt — hver fredag.

Indtjening

Ingen indtjening endnu. Den vises her, efter din første session er afholdt og afregnet.

Udbetalinger

Ingen udbetalinger endnu.
X-rayevery figure above comes from compute.ts, run in your browser

The calls this step makes

None yet. Press play, or pick a day on the timeline.

The page reads the ledger, Stripe's balance and the invoices; on the live site that's Supabase and Stripe, here the same numbers come from the engine.

Chapter 05Therapist sites

Every therapist, a site of their own.Every therapist,a site of their own.

The problem

Therapists want to send their own clients somewhere that's theirs, not to a listing among dozens of others.

The call

A subdomain for every therapist, rewritten at the edge to their page, four templates to choose from, and one login across all of them.

The result

maja-holm.terapimatch.dk is their site, with their colours and their calendar, and clients who book through it pay the own-link rate.

slugmaja-holm

Try “Søren Ærø”, or “admin”.

  1. *.terapimatch.dkOne wildcard domain and one wildcard certificate: a certificate per therapist would hit Let's Encrypt's 50-a-week limit.
  2. proxy.ts · updateSession()The session is refreshed first; the cookie is scoped to .terapimatch.dk, so one login works on every subdomain.
  3. bareSubdomain(host) → "maja-holm"Only a bare label counts: the apex, www, multi-label and foreign hosts return null.
  4. rewrite → /terapeut/maja-holmRewritten, not redirected: the address stays theirs, with x-tm-standalone: 1 on the request.
  5. their site · no marketplace chromeThe standalone header drops the way back to the directory.
🔒maja-holm.terapimatch.dk

From the logbook

Logged out on every click, but only in Chrome.

After the move from .com to .dk, the session cookie, which Supabase splits into chunks, was being written at two scopes at once. The browser sent both; the server stitched a token from halves of two. Written up, fixed, and caught before a single real user had an account.

sb-…-auth-token.0www.terapimatch.dkeyJhbGciOi…Q1

sb-…-auth-token.1www.terapimatch.dk…xY2-9fK3

sb-…-auth-token.0.terapimatch.dkeyJhbGciOi…Zp

sb-…-auth-token.1.terapimatch.dk…Wq7-LmP0

Chapter 06Scheduled jobs

It keeps its own hours.It keepsits own hours.

The problem

Reminders, payouts, lapsed holds and invoices can't wait for someone to click a button.

The call

Seven jobs on Vercel's scheduler, each one safe to run twice, each one locked behind a secret that fails closed.

The result

Sessions are paid out within the hour they end, and nothing is sent, paid or invoiced twice.

:00:15:30:4513:57:00UTC · runs in arn1, Stockholm

Drag the hand to scrub the hour.

/api/cron/remindersevery hour, :00Sends booking reminders by the admin's rules, each one once.twice is once: a send is recorded per booking and rule
/api/cron/onboardingevery hour, :10Follows up with therapists who stall on the way to a live page.twice is once: it tracks the stage each therapist is at
/api/cron/sweep-holdsevery hour, :15Tidies reservations whose 15 minutes ran out. Cleanup, not correctness: the booking functions already expire them inside the lock.twice is once: only touches holds already past their time
/api/cron/calendar-syncevery hour, :20Mirrors each therapist's other Google calendars into the dashboard. The main calendar arrives by push, in real time.twice is once: gated per connection by when it last ran
/api/cron/settlementevery hour, :30Pays therapists for sessions that have ended, minus the commission, through Stripe Connect.twice is once: a unique settlement_key per session
/api/cron/reconciliationevery night, 03:45 UTCReads Stripe and the ledger side by side and records any difference. Changes nothing.twice is once: read-only: it records, never changes
/api/cron/invoicesthe 1st, 04:00 UTCIssues last month's commission invoices, numbered without gaps, as PDFs.twice is once: one invoice per therapist per month

Every job checks CRON_SECRET first, and if it isn't set, refuses to run at all.

(In numbers)

Counted in the repo.Countedin the repo.

4
months from the first commit to live
726
commits of mine
183
database migrations
84
Postgres tables
101
Postgres functions
100
pages
24
kinds of email
3
calendar providers
7
scheduled jobs
0
floats in the commission math

What I'd do next

  1. 01Run the slot and commission verifiers in CI on every push; today they're scripts I run by hand.
  2. 02Put automated tests around the Postgres functions themselves, so the booking guarantees are proven on every change, not only when I check them.
  3. 03Give session payouts the row lock clip payouts already take, closing the last microseconds in which a cancel and a transfer can cross.
Let's talk