Samples / September 29, 2026

Strata: Social Habit Tracker

Target: Replit Category: Consumer App Downstream: Vibe Coding Prompt Pack

Architecture Design Document

Architecture Design Document

TL;DR

"The takeaway is that Strata is a production Replit and Node.js architecture blueprint generated by Zalcro. It uses a single-process Express server, managed PostgreSQL, and in-process node-cron scheduling to deliver a complete social habit tracker without requiring any external DevOps or worker dynos."

Strata is a social habit tracker where users build daily routines, track streaks, and hold each other accountable through public habits and friend partnerships. It's built entirely on Replit using a PostgreSQL database, a Node.js backend, and a React frontend. The most important architectural choices are using Replit's managed PostgreSQL for zero-ops database hosting and Resend for dead-simple email delivery.

Executive Summary

The system is a full-stack web application deployed on Replit as a single project. The backend is an Express.js REST API serving a React SPA from the same Node.js process. Authentication is handled by Passport.js supporting both local email/password and Google OAuth. Data lives in a Neon-powered PostgreSQL database provisioned directly through Replit's database tooling, accessed via Drizzle ORM for type-safe queries and schema migrations.

The social layer — public habit discovery, accountability partnerships, and leaderboards — is modeled relationally from day one so nothing needs to be rearchitected as the feature set expands. Email reminders and invite notifications are sent through Resend, triggered by a lightweight cron job running inside the same Node.js process.

The key tradeoffs are: collocating the cron scheduler with the web server keeps infrastructure minimal for a solo founder but means reminders miss if the server is restarted exactly at the scheduled minute (tolerable given the stated availability posture); and using a single Replit deployment avoids DevOps complexity at the cost of some scaling headroom that won't be needed until well past 10,000 users.

System Overview

graph TD
    subgraph Client["Client"]
        browser["Web Browser\n(React SPA)"]
    end

    subgraph Replit["Replit Deployment"]
        subgraph Server["Express Server Process"]
            api["API Routes\n(Express 4.19)"]
            auth["Auth Module\n(Passport.js)"]
            habitEngine["Habit & Check-in\nEngine"]
            socialEngine["Social & Discovery\nEngine"]
            scheduler["Background Scheduler\n(node-cron)"]
        end

        subgraph Assets["Static Assets"]
            spa["React Bundle\n(Vite build output)"]
        end
    end

    subgraph Data["Data Layer"]
        db[("PostgreSQL 16\n(Neon via Replit)")]
        sessions["Session Store\n(connect-pg-simple)"]
    end

    subgraph External["External Services"]
        resend["Resend\n(Email API)"]
        google["Google OAuth 2.0"]
    end

    browser -->|"API requests"| api
    browser -->|"Loads SPA"| spa
    api --> auth
    api --> habitEngine
    api --> socialEngine
    auth -->|"Session read/write"| sessions
    auth -->|"OAuth callback"| google
    habitEngine -->|"Queries & writes"| db
    socialEngine -->|"Queries & writes"| db
    auth -->|"User upsert"| db
    scheduler -->|"Reminder query"| db
    scheduler -->|"Send reminder"| resend
    socialEngine -->|"Send invite email"| resend
    sessions --- db

The user's browser communicates exclusively with the Express API, which handles all business logic. The API reads and writes from PostgreSQL via Drizzle ORM. Session state is stored server-side in the database using connect-pg-simple, so sessions survive server restarts.

A background scheduler (node-cron, running inside the same process) fires at regular intervals — once per minute — to check which users have a reminder due and haven't completed the associated habit. When it finds matches, it calls Resend to send the reminder email. The same Resend integration handles accountability partner invitation emails.

The React frontend is compiled to a static bundle at build time and served by Express from a /public directory. There is no separate frontend hosting or CDN at launch; Replit's built-in serving handles it. This keeps the deployment to a single Replit Repl.

Data flows in one direction for the social features: users opt their habits into public visibility, which makes them queryable by the "popular habits" discovery endpoint. Accountability partnerships are symmetric — both users must accept before either can see the other's public streaks.

Architectural Constraints Summary

The Replit constraint is the single biggest architectural driver. Because Replit runs a single persistent process, there's no separate worker dyno, no job queue service, and no managed cron. This rules out a decoupled worker architecture — the scheduler must live in the API process. It also means the deployment strategy is "push code, Replit restarts the process" — no Docker, no CI pipeline, no staging environment.

The data architecture constraint (relational, must scale without rearchitecting) drove the decision to model the full social graph and all planned features in the initial schema, even features that aren't in the first release. This costs nothing at setup time and prevents painful migrations later.

The lowest-cost constraint, combined with the Replit ecosystem preference, resolves directly to Replit's native PostgreSQL integration (backed by Neon), which has a free tier sufficient for the first several months of growth.

The security constraint requiring both email/password and social login is met by Passport.js, which is the de facto standard for multi-strategy auth in Express without adding a managed auth service that would cost money and add an external dependency.

The email sending constraint ("whatever Replit's ecosystem makes easiest") resolves to Resend — it has a generous free tier, a clean Node.js SDK, and no SMTP configuration required.

Component Architecture

Express API Server

Handles all HTTP routing, authentication middleware, request validation, and response formatting. Organized into route modules by domain: auth, habits, check-ins, reminders, social (partnerships + leaderboards), and user management. Uses express-session backed by connect-pg-simple so session data persists across deploys. Input validation uses Zod schemas at the route layer — invalid requests are rejected before they reach business logic.

Authentication Module (Passport.js)

Two strategies: LocalStrategy for email/password (passwords hashed with bcrypt, 12 rounds), and GoogleStrategy for OAuth 2.0. On successful auth, both strategies upsert a user record and establish a session. The Google strategy stores the OAuth provider ID alongside the email so users who signed up via Google can't accidentally create a duplicate account via local strategy.

Habit & Check-in Engine

Implements the core business logic: habit creation with recurrence rules (specific days of week), completion recording (multiple check-ins per day are allowed), streak calculation, and note/journal entry attachment to a check-in. Streak calculation runs on read rather than being stored as a counter — this avoids the classic "stale streak" bug where the stored counter drifts from reality. For each habit, the streak is computed by walking backwards from today through consecutive days where the habit was due and completed. Results are cached in-process for the duration of a request; there is no cross-request cache at this scale.

Social & Discovery Engine

Manages accountability partner invitations (invite → pending → accepted/rejected state machine), public habit follower counts (a simple count query over the habit_templates matching by normalized name), and leaderboard queries (ranked by current streak length for public habits in a given category or globally). Public habit counts are computed on read using an indexed query — no denormalized counter that can drift.

Background Scheduler (node-cron)

Runs inside the Express process. At startup, schedules a job that fires every minute. Each tick queries for reminder configurations where: the current time matches the user's configured reminder time (within the current minute window), the habit is due today, and no completion record exists for today. For each match, it enqueues an email send via Resend. The scheduler does not retry failed sends — if Resend is down, that minute's reminders are skipped. This is acceptable given the stated availability posture.

Resend Email Client

A thin wrapper around the Resend Node.js SDK. Used by both the scheduler (reminder emails) and the social engine (invitation emails). All emails use a common "from" address configured via environment variable. Templates are defined as plain HTML strings in the codebase — no separate template service.

Drizzle ORM Layer

Provides type-safe query building and schema-as-code. Migrations are generated via Drizzle Kit and applied manually by running a script in the Replit Shell. Schema definition is the source of truth for all table structures and constraints.

Data Architecture

Users

Stores identity, auth credentials, and timezone. The timezone field is essential for correct reminder scheduling and streak calculation — "today" is relative to the user's local time.

Entity Attribute Type + Constraints Business Rule & Access Control
User id UUID, PK System-generated; immutable
User email TEXT, UNIQUE NOT NULL Used as login identifier; must be verified before social login is linked
User password_hash TEXT, NULLABLE Null when user authenticated via OAuth only
User google_id TEXT, UNIQUE NULLABLE Set when Google OAuth strategy resolves
User timezone TEXT NOT NULL, DEFAULT 'UTC' Used for streak calculation and reminder scheduling
User created_at TIMESTAMPTZ NOT NULL Set on insert; immutable

Habits

The core domain entity. Each habit belongs to one user. The is_public flag controls social visibility. recurrence_days stores which days of the week the habit is active as an integer array (0 = Sunday … 6 = Saturday).

Entity Attribute Type + Constraints Business Rule & Access Control
Habit id UUID, PK System-generated
Habit user_id UUID, FK → User NOT NULL Owner; only owner can modify or delete
Habit name TEXT NOT NULL Normalized (lowercased, trimmed) copy stored in name_normalized for matching across users
Habit name_normalized TEXT NOT NULL, INDEXED Used for public habit count queries
Habit category TEXT NULLABLE Used for leaderboard filtering
Habit is_public BOOLEAN NOT NULL DEFAULT false When true, visible in public discovery and counts; accountability partners can always see public habits of their partners
Habit recurrence_days INTEGER[] NOT NULL Days of week habit is active; must be non-empty
Habit archived_at TIMESTAMPTZ NULLABLE Soft-delete; archived habits excluded from active queries but retained for history

CheckIns

Records each completion of a habit. Multiple per day are allowed. Journal notes attach here.

Entity Attribute Type + Constraints Business Rule & Access Control
CheckIn id UUID, PK System-generated
CheckIn habit_id UUID, FK → Habit NOT NULL Cascades on habit archive (records retained)
CheckIn user_id UUID, FK → User NOT NULL Redundant FK for query efficiency; must match habit owner
CheckIn checked_at TIMESTAMPTZ NOT NULL Server-set timestamp; used for streak and reminder logic
CheckIn note TEXT NULLABLE Journal entry for this completion

Reminders

One or more reminder configurations per habit. Each record stores the time-of-day to send.

Entity Attribute Type + Constraints Business Rule & Access Control
Reminder id UUID, PK System-generated
Reminder habit_id UUID, FK → Habit NOT NULL Cascade delete when habit is deleted
Reminder user_id UUID, FK → User NOT NULL For efficient scheduler queries without joining Habit
Reminder remind_at_time TIME NOT NULL Local time in user's timezone; scheduler converts to UTC for comparison

AccountabilityPartners

Models the friend invitation and acceptance flow.

Entity Attribute Type + Constraints Business Rule & Access Control
AccountabilityPartner id UUID, PK System-generated
AccountabilityPartner requester_id UUID, FK → User NOT NULL User who sent the invite
AccountabilityPartner addressee_id UUID, FK → User NOT NULL User who received the invite
AccountabilityPartner status TEXT NOT NULL, CHECK IN ('pending','accepted','rejected') Only addressee can change status; UNIQUE constraint on (requester_id, addressee_id)
AccountabilityPartner created_at TIMESTAMPTZ NOT NULL Set on invite

Data Lifecycle

All user data — habits, check-ins, reminders, notes, and partnership records — is retained for the lifetime of the account. On account deletion, a cascading delete from the User row removes all associated data. Archived habits (soft-deleted) are retained in-table; if the volume of archived records becomes a performance concern past 10,000 users, a scheduled cleanup job can prune records older than two years.

Integration Architecture

Resend (Email)

Used for two flows: reminder emails and accountability partner invitation emails. The Resend API key is stored as a Replit Secret (environment variable). The Node.js SDK sends transactional email by constructing a message with a recipient, subject, and HTML body, then calling the send operation. The "from" address is a verified sender domain configured in the Resend dashboard.

For reminder emails: if the Resend API call fails (network error or API error), the failure is logged to stdout and the reminder is skipped for that tick. There is no retry queue. The next day's configured reminder will fire as normal.

For invitation emails: if the send fails, the API route returns an error response to the client so the user knows to try again. The invitation record is not created until the email send succeeds, keeping the database consistent with what the invitee actually received.

Google OAuth 2.0

Passport.js GoogleStrategy handles the OAuth flow. The client ID and client secret are stored as Replit Secrets. On successful callback, the strategy fetches the user's email and Google profile ID. If the email matches an existing local account, the Google ID is linked to that account. If the Google account is new, a new User record is created with a null password hash. If Google's OAuth service is unavailable at login time, users fall back to email/password login — the two strategies are independent.

Security Architecture

Authentication & Sessions

Sessions are stored server-side in PostgreSQL via connect-pg-simple. The session cookie is httpOnly, sameSite: strict, and secure: true (Replit serves over HTTPS). Session secret is stored as a Replit Secret, never in source code. Sessions expire after 30 days of inactivity.

Password Security

Passwords are hashed with bcrypt at 12 rounds before storage. Plain-text passwords never touch the database layer. Password reset is out of scope for launch; users who forget their password can use Google OAuth if linked, or contact support.

Input Validation

All API request bodies and query parameters are validated with Zod schemas at the route layer. Unknown fields are stripped. Strings are trimmed. Requests that fail validation are rejected with a descriptive error before reaching the ORM. The name_normalized field is computed server-side — never accepted from the client.

Authorization

Every API route that touches a habit, check-in, or reminder verifies that the requesting user owns the resource. Public habit queries are scoped to only return is_public=true records. Accountability partner visibility is gated on accepted partnership status — a pending invite does not expose either user's data to the other.

Secrets Management

All secrets (database URL, session secret, Resend API key, Google OAuth credentials) are stored as Replit Secrets, which are injected as environment variables at runtime. They are never committed to the Repl's source files.

Error Handling Policy

API error responses include a human-readable message but never expose stack traces, internal IDs, or database error details to the client. Errors are logged to stdout with context (route, user ID if available) for debugging via Replit's built-in log viewer.

Deployment Hardening

The Express app sets security headers via the helmet middleware package (default configuration), which covers X-Content-Type-Options, X-Frame-Options, and Referrer-Policy, among others. CORS is configured to allow requests only from the Replit app's own origin — no wildcard. HTTPS is enforced by Replit's reverse proxy; the Express app does not need to handle TLS termination.

Deployment Architecture

Single Repl, Single Process

The entire system — Express API, static React bundle, and node-cron scheduler — runs as one Node.js process in a single Replit Repl. Replit's "Always On" feature (available on paid plans) keeps the process running between requests so the cron scheduler fires reliably. Without Always On, Replit spins down idle Repls and reminders would not fire during sleep periods.

Build Process

The React frontend is bundled with Vite at build time (vite build). The output is placed in a /public directory that Express serves statically. The Replit start command runs vite build && node server.js. On code changes, the developer re-runs this command from the Replit Shell or configures the Repl's run button to do so.

Database Migrations

Drizzle Kit generates SQL migration files from schema changes. Migrations are applied by running drizzle-kit migrate in the Replit Shell before restarting the server. There is no automated migration runner at startup — this prevents accidental schema changes on deploy.

Environments

There is one environment: production. There is no staging. Testing happens locally in the Replit editor against the live database (acceptable given the solo maintainer and stated ops posture). A separate "dev" Repl with its own database can be created manually if needed but is not required.

Scaling

Replit's infrastructure handles horizontal scaling to a limited degree, but the single-process design means the in-process cron scheduler does not scale horizontally — running two instances would double-send reminders. At the stated 1,000–10,000 user target, a single process is sufficient. If usage grows beyond that, the scheduler can be extracted to a separate Repl or replaced with a managed service like Trigger.dev without changing the database schema.

Technology Stack

Technology Version Role Why chosen
Node.js 20 LTS Runtime Replit's best-supported runtime; matches the JS/TS stack end-to-end
Express.js 4.19 HTTP server and API Minimal, widely understood, no magic — appropriate for a solo maintainer
React 18.3 Frontend UI Dominant ecosystem, excellent Replit support, pairs well with Vite
Vite 5.3 Frontend bundler Fast builds, simple config, native TypeScript support
TypeScript 5.5 Language Type safety across frontend and backend; Drizzle ORM requires it for full benefit
Drizzle ORM 0.31 Database access and migrations Lightweight, schema-as-code, excellent TypeScript inference, Neon-compatible
PostgreSQL 16 (via Neon/Replit) Primary database Replit's native managed offering; relational structure matches the data model
Passport.js 0.7 Authentication Multi-strategy auth (local + Google OAuth) without a managed auth service
bcrypt 5.1 Password hashing Industry standard; 12 rounds balances security and latency
express-session + connect-pg-simple 1.18 / 7.0 Server-side sessions Database-backed sessions survive restarts; no Redis dependency
node-cron 3.0 In-process job scheduler Zero dependencies, simple API, sufficient for single-process reminder scheduling
Zod 3.23 Input validation Composable schemas, TypeScript inference, used on both client (form validation) and server (request validation)
Resend 3.2 Transactional email Generous free tier, simple Node.js SDK, no SMTP setup, good deliverability
Helmet.js 7.1 HTTP security headers One-line Express middleware for baseline security hardening

Key Architectural Decisions

Decision: Run the cron scheduler inside the Express process

Alternatives: separate Replit Repl as a worker, external cron service like EasyCron calling a webhook endpoint. The in-process scheduler wins because it requires zero additional infrastructure, no inter-service auth, and no additional cost. The tradeoff — reminders miss if the server restarts at exactly the wrong moment — is acceptable given the stated availability posture ("annoying but tolerable"). If Always On is enabled, restarts are rare enough that this is a non-issue in practice.

Decision: Compute streaks on read rather than storing a counter

Alternatives: store current_streak as an integer on the Habit row and update it on every check-in. On-read calculation wins because it is always correct — a stored counter can drift if check-ins are deleted, habits are archived and restored, or the server crashes mid-update. At 10,000 users, streak calculation over indexed check-in records is fast enough that caching is not needed. Caching can be added later if profiling shows it as a bottleneck.

Decision: Use Resend for email instead of SMTP or SendGrid

Alternatives: Nodemailer with Gmail SMTP (unreliable for transactional volume, rate-limited), SendGrid (more complex setup, higher cost at low volume). Resend's free tier covers 3,000 emails/month, the SDK is three lines to configure, and there is no SMTP credential management. It is the lowest-friction path for the stated goal.

Decision: Serve the React SPA from the same Express process

Alternatives: separate Replit Repl for the frontend, Cloudflare Pages. Collocating frontend and backend in one Repl eliminates cross-origin complexity, halves the number of things to manage, and costs nothing extra. The only downside is that a frontend-only redeploy requires restarting the whole process — at this scale and team size, that is not a meaningful constraint.

Decision: Use Drizzle ORM with Neon/Replit PostgreSQL

Alternatives: Prisma (heavier, slower cold starts, own migration engine), raw pg queries (no type safety). Drizzle's schema-as-code approach means the database structure is version-controlled and the TypeScript types are automatically correct. It is lighter than Prisma and has first-class Neon/serverless-pg support, which matches Replit's managed database offering.

Decision: Model the full social schema on day one

Alternatives: start with a minimal schema and add social tables later. Full upfront modeling wins because the social features (leaderboards, partnerships, public habit counts) are defined as day-one requirements in the constraints, and schema changes to add FKs or junction tables to an existing populated database are painful. The extra tables cost nothing until they have data.

Error Handling & Failure Modes

Invalid user input

Zod validation at the route layer rejects malformed requests before they reach business logic. The client receives a structured error describing which fields failed. Nothing is written to the database.

Unauthenticated or unauthorized requests

The session middleware rejects requests with no valid session cookie with an authentication error response. Authorization checks (ownership of a habit, accepted partnership status) return a "not found" style response rather than "forbidden" to avoid leaking information about whether the resource exists.

Duplicate accountability partner invite

The UNIQUE constraint on (requester_id, addressee_id) in the AccountabilityPartner table prevents duplicate invites at the database level. The API catches the constraint violation and returns a user-readable error ("You already have a pending invite with this user") rather than a generic server error.

What happens if the Resend API is down when the scheduler fires?

The scheduler catches the error from the SDK, logs the failure with the affected user ID and habit ID to stdout, and continues to the next reminder in the queue. The failed reminder is not retried. The user will not receive the reminder for that day. The scheduler runs again the next day at the configured time as normal. Pre-launch verification: use Resend's test API mode (which accepts sends without actually delivering them) to confirm the scheduler fires and handles errors correctly.

What happens if Resend is down when an invitation email is sent?

The API route catches the send failure and returns an error response to the client. The AccountabilityPartner record is not written to the database. The inviting user sees an error message and can retry. No orphaned invitation record is created. Pre-launch verification: simulate by temporarily providing an invalid API key in the Replit Secrets and confirming the invite flow shows an error without creating a database record.

What happens if the database connection is lost during a check-in write?

Drizzle's underlying pg client will throw. The Express error handler catches it, returns a server error response to the client, and logs the failure. The check-in is not recorded. The user will see an error and can try again — check-ins are idempotent from the user's perspective (multiple per day are allowed) so a retry creates a new record without corrupting history.

Streak calculation returning wrong results after timezone change

If a user changes their timezone setting, historical check-in timestamps (stored as UTC) are reinterpreted against the new timezone, which may change which "day" a check-in belongs to and break the streak count. This is an edge case at launch. The mitigation is to document in the UI that changing timezone resets streak display, and to store checked_at in UTC (which Drizzle does by default with TIMESTAMPTZ).

Cron scheduler double-firing if somehow two processes start

Replit runs one process per Repl, so this is not a realistic risk in the current architecture. If the app is later scaled horizontally, double-sends become a risk. The mitigation at that point is to extract the scheduler to a dedicated Repl or use a distributed lock — but this is out of scope until the architecture changes.

Google OAuth unavailable at login

The LocalStrategy is independent of Google's services. Users with email/password accounts can log in normally. Users who only have a Google OAuth account cannot log in until Google's service recovers. The login page should make both options visibly available so users aren't confused. Pre-launch verification: test the local login flow without any Google credentials configured.

Risks and Mitigations

Risk 1: Reminder reliability depends on Replit Always On

Stems from the in-process cron scheduler decision. If Always On is not enabled (or lapses due to billing), the Repl sleeps after inactivity and scheduled reminders don't fire. Users receive no reminders until the Repl wakes up (on the next HTTP request). Impact: core feature silently stops working, potentially driving churn. Mitigation: enable Always On from day one (it requires a Replit paid plan, which is a known cost), and display a server health endpoint that the developer can manually check if users report missing reminders.

Risk 2: Schema migrations have no automated safety net

Stems from the manual migration approach. A developer running the wrong migration script or forgetting to run it before deploying new code can cause the app to crash or silently corrupt data. Impact: downtime or data loss. Mitigation: Drizzle Kit generates reversible SQL migration files — always review the generated SQL before applying. Keep a manual snapshot of the Neon database before any significant schema change (Neon supports point-in-time restore on paid plans).

Risk 3: Public habit name normalization creates matching collisions

Stems from the decision to match public habits by normalized name to show follower counts. Users naming a habit "Exercise" vs "exercise" vs "Exercise " will be correctly grouped, but semantically different habits with the same normalized name (e.g., "read" meaning "read a book" vs "read the news") get counted together. Impact: misleading follower counts that erode trust in the social feature. Mitigation: introduce category-scoped matching at launch (normalized name + category must both match) to reduce false groupings, and add a habit template / canonical name feature post-launch.

Risk 4: Email deliverability degrades if sending domain is not properly verified

Stems from the Resend integration. If the custom "from" domain is not SPF/DKIM configured, reminder and invitation emails land in spam. Impact: users miss reminders, think the app is broken, or never accept partnership invites. Mitigation: complete Resend's domain verification checklist before sending any production email. Use Resend's deliverability testing tools to confirm emails land in inbox for major providers (Gmail, Outlook) before launch.

Risk 5: Streak calculation becomes slow as check-in history grows

Stems from the on-read streak calculation approach. For a user with two years of daily check-ins across 20 habits, a single page load could trigger 20 backward-walking queries. Impact: slow page loads that worsen as the user base and their history grows. Mitigation: the checked_at column on CheckIns must have a composite index on (habit_id, checked_at DESC) from day one. If profiling later shows this is still slow, add a daily background job that snapshots the current streak count to a denormalized column — the architecture supports this addition without structural change.

Implementation Plan

Implementation Plan

Environment Setup

What you'll need

Before any code gets written, you'll need a few accounts set up and connected. This section walks you through exactly what to create and configure so everything works the first time the app runs.

Accounts to create

  • Replit — replit.com — Where your entire app lives and runs. You'll need a paid plan (Core or higher) to enable Always On, which keeps your reminder scheduler firing reliably around the clock.
  • Resend — resend.com — Handles all outgoing email: habit reminders and accountability partner invitations. The free tier covers 3,000 emails per month, which is plenty to start.
  • Google Cloud Console — console.cloud.google.com — Needed only to enable Google sign-in. You'll create an OAuth app here and get a client ID and secret.

Before you start

Replit setup

  1. Create a new Repl using the Node.js template.
  2. Enable Always On for your Repl (found in the Repl's settings panel). This is what keeps your reminder scheduler alive between requests.
  3. Replit will provision a PostgreSQL database for your Repl automatically when you add it through the Database tool in the left sidebar. Do this before running any code — your app needs the database URL to start.
  4. Note your Repl's public URL (it looks like https://your-repl-name.your-username.replit.dev). You'll need this when setting up Google OAuth.

Resend setup

  1. After signing up, go to Domains and add the domain you want to send email from (even a subdomain like mail.yourdomain.com works).
  2. Follow Resend's instructions to add the SPF and DKIM DNS records to your domain. Your emails will land in spam without this step — don't skip it.
  3. Once the domain is verified, create an API key from the API Keys section. Copy it immediately; you won't see it again.
  4. Confirm your verified sender address (e.g., reminders@mail.yourdomain.com). This is the "from" address for all emails the app sends.

Google OAuth setup

  1. In Google Cloud Console, create a new project.
  2. Go to APIs & Services → OAuth consent screen. Set the app name, add your email as a support contact, and publish it (or leave it in testing mode while you're building).
  3. Go to APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID. Choose "Web application."
  4. Under "Authorized redirect URIs," add: https://your-repl-url.replit.dev/auth/google/callback — replacing the domain with your actual Repl URL from above.
  5. Copy the Client ID and Client Secret.

Environment variables

Add each of these to your Repl's Secrets panel (the padlock icon in the sidebar) — never paste them into your source files.

  • DATABASE_URL — Replit sidebar → Database → connection string (auto-populated when you add the database)
  • SESSION_SECRET — generate any long random string (32+ characters); you choose this value
  • RESEND_API_KEY — Resend dashboard → API Keys → your key
  • EMAIL_FROM — the verified sender address you configured in Resend (e.g., reminders@mail.yourdomain.com)
  • GOOGLE_CLIENT_ID — Google Cloud Console → Credentials → your OAuth 2.0 client
  • GOOGLE_CLIENT_SECRET — same location as above
  • APP_URL — your full Repl URL, e.g., https://your-repl-name.your-username.repl.co

Phases

Phase 1: Project Scaffold and Database Schema

This phase establishes the complete project structure, TypeScript configuration, and the full database schema as defined in the ADD. Getting the schema right here prevents painful migrations later — every table, index, and constraint defined in the ADD is created now, including social tables that aren't wired to features yet. By the end of this phase, the database is ready and Drizzle's type-safe query layer is available to every subsequent phase.

Contracts

db/schema.ts

Exports the complete Drizzle table definitions. Every later phase imports its types from here — nothing redefines a table shape elsewhere.

  • users — columns: id (UUID PK), email (text, unique not null), password_hash (text, nullable), google_id (text, unique nullable), timezone (text not null, default 'UTC'), created_at (timestamptz, not null)
  • habits — columns: id (UUID PK), user_id (UUID FK → users, not null), name (text not null), name_normalized (text not null, indexed), category (text, nullable), is_public (boolean not null, default false), recurrence_days (integer array, not null), archived_at (timestamptz, nullable)
  • check_ins — columns: id (UUID PK), habit_id (UUID FK → habits, not null), user_id (UUID FK → users, not null), checked_at (timestamptz not null), note (text nullable); composite index on (habit_id, checked_at DESC)
  • reminders — columns: id (UUID PK), habit_id (UUID FK → habits, not null, cascade delete), user_id (UUID FK → users, not null), remind_at_time (time, not null)
  • accountability_partners — columns: id (UUID PK), requester_id (UUID FK → users, not null), addressee_id (UUID FK → users, not null), status (text not null, check constraint: one of 'pending', 'accepted', 'rejected'), created_at (timestamptz not null); unique constraint on (requester_id, addressee_id)
  • sessions — columns required by connect-pg-simple: sid (text PK), sess (jsonb not null), expire (timestamptz not null); index on expire

Exported TypeScript types (inferred by Drizzle):

  • User, NewUser — select and insert shapes for users
  • Habit, NewHabit — select and insert shapes for habits
  • CheckIn, NewCheckIn — select and insert shapes for check_ins
  • Reminder, NewReminder — select and insert shapes for reminders
  • AccountabilityPartner, NewAccountabilityPartner — select and insert shapes for accountability_partners

db/index.ts

Exports a single db instance (the Drizzle client connected to DATABASE_URL). Every module that needs database access imports db from here — there is no second connection anywhere in the codebase.

  • db — the Drizzle database client; type is the Drizzle instance parameterized over the schema

db/migrations/

Directory where Drizzle Kit writes generated SQL migration files. Not a module — no exports. Applied manually via drizzle-kit migrate in the Replit Shell.

drizzle.config.ts

Drizzle Kit configuration file at project root. Points to db/schema.ts as the schema source and db/migrations/ as the output directory. Uses DATABASE_URL from the environment.

tsconfig.json and package.json

  • TypeScript configured for Node 20 (module: ESNext or CommonJS — pick one and it must match every import style used in later phases; CommonJS is recommended for Express compatibility on Replit)
  • package.json scripts:
    • "build" → "vite build"
    • "start" → "node dist/server.js" (or the compiled entry point, depending on the TS compile target chosen above)
    • "dev" → "tsx watch server/index.ts" for local iteration

Deliverables:

  • Running drizzle-kit generate produces a valid SQL migration file with all six tables, indexes, and constraints
  • Running drizzle-kit migrate against the Replit database applies the migration without errors
  • db/index.ts exports a db client that can execute a simple SELECT 1 query without throwing

Phase 2: Express Server, Session Middleware, and Security Baseline

This phase stands up the Express application with all middleware wired in the correct order: Helmet, CORS, session (backed by the PostgreSQL sessions table from Phase 1), and a static file handler for the future React bundle. The server starts, responds to a health check, and enforces the security baseline described in the ADD before any route logic exists.

Contracts

server/index.ts

The application entry point. Imports and mounts everything in this order: Helmet, CORS, JSON body parser, session middleware, Passport initialization (Passport itself is configured in Phase 3 — this phase just mounts the passport.initialize() and passport.session() middleware stubs), static file serving from /public, the router (Phase 3+), and the global error handler.

Exports nothing — this is the process entry point.

Configuration values consumed from environment variables:

  • SESSION_SECRET — passed to express-session
  • APP_URL — used as the only allowed CORS origin
  • DATABASE_URL — consumed by connect-pg-simple for session storage

Session configuration:

  • Cookie: httpOnly: true, sameSite: 'strict', secure: true
  • Store: connect-pg-simple using the db connection
  • Max age: 30 days

server/middleware/errorHandler.ts

Exports a single Express error-handling middleware:

  • errorHandler(err, req, res, next): void
  • Logs the error to stdout with the route path and req.user?.id if available
  • Responds with { error: string } — the message is human-readable but never includes a stack trace, internal ID, or database error detail
  • If the error carries a known application error type (see below), maps it to the appropriate HTTP status; all unrecognized errors respond as a generic server error

server/errors.ts

Defines the application's error types. All phases use these — never throw raw database errors or SDK errors across a module boundary.

  • AppError — base class, takes message: string and statusCode: number
  • NotFoundError extends AppError — status 404; used when a resource doesn't exist or the caller isn't authorized to know it exists
  • UnauthorizedError extends AppError — status 401; used when no valid session exists
  • ValidationError extends AppError — status 400; used when Zod rejects input
  • ConflictError extends AppError — status 409; used for constraint violations (e.g., duplicate partnership invite)
  • ExternalServiceError extends AppError — status 502; used when Resend or Google OAuth fails in a way the caller should know about

server/router.ts

A barrel that mounts all domain route modules under their path prefixes. In this phase it is empty (exports an Express Router with no routes). Later phases add their route modules here without touching server/index.ts.

Deliverables:

  • Server starts and responds to GET /health with { status: 'ok' }
  • A request with an invalid CORS origin receives a CORS rejection
  • A request to an undefined route returns a 404 response formatted as { error: string } (not Express's default HTML 404)
  • Helmet headers (X-Frame-Options, X-Content-Type-Options, etc.) are present on every response

Phase 3: Authentication — Local and Google OAuth

This phase implements the full authentication system: Passport.js LocalStrategy and GoogleStrategy, the session serialization/deserialization cycle, and the auth route handlers. By the end users can register, log in with email/password, log in with Google, and log out. The requireAuth middleware that all later phases depend on is also defined here.

Contracts

server/auth/passport.ts

Configures both Passport strategies and session serialization. Exports nothing — called once from server/index.ts for its side effects.

LocalStrategy behavior:

  1. Look up the user by email (case-insensitive)
  2. If no user found, fail with the message 'Invalid email or password'
  3. Compare the submitted password against password_hash using bcrypt
  4. If the hash doesn't match, fail with the same message (do not distinguish between "no user" and "wrong password")
  5. On success, pass the full User object to the done callback

GoogleStrategy behavior:

  1. Receive the Google profile's email and google_id (the profile's id field)
  2. Look up an existing user by google_id first
  3. If found, pass that user to done
  4. If not found by google_id, look up by email
  5. If found by email, update that user's google_id to link the accounts, pass the updated user
  6. If neither match, create a new User with password_hash: null, set google_id, pass the new user
  7. On any database error, pass the error to done

Session serialization:

  • serializeUser: stores user.id (string) in the session
  • deserializeUser: looks up the full User by id; if not found, passes null (Passport handles this as a logged-out state)

server/auth/routes.ts

Exports an Express Router mounted at /auth.

  • POST /auth/register

    • Accepts: { email: string, password: string } — validated by Zod; password minimum 8 characters
    • Behavior: check for existing email (case-insensitive); if taken return ConflictError; hash the password; insert a new User; establish a session; return { user: PublicUser }
    • PublicUser shape: { id: string, email: string, timezone: string } — never includes password_hash or google_id
  • POST /auth/login

    • Accepts: { email: string, password: string }
    • Delegates to Passport LocalStrategy; on success return { user: PublicUser }; on failure return UnauthorizedError
  • GET /auth/google

    • Initiates Google OAuth redirect; no request body
  • GET /auth/google/callback

    • OAuth callback; on success redirect to /; on failure redirect to /login?error=oauth_failed
  • POST /auth/logout

    • Destroys the session; returns { success: true }
  • GET /auth/me

    • Requires requireAuth; returns { user: PublicUser } for the current session's user

server/middleware/requireAuth.ts

Exports a single Express middleware:

  • requireAuth(req, res, next): void
  • If req.isAuthenticated() is true, calls next()
  • Otherwise throws UnauthorizedError

Used by every protected route in all later phases.

server/auth/validation.ts

Exports Zod schemas used in auth routes:

  • registerSchema — { email: z.string().email(), password: z.string().min(8) }
  • loginSchema — same shape

Deliverables:

  • POST /auth/register with a valid body creates a user, returns a PublicUser, and sets a session cookie
  • POST /auth/login with correct credentials returns a PublicUser and sets a session cookie
  • POST /auth/login with wrong credentials returns a 401 with { error: 'Invalid email or password' }
  • GET /auth/me with a valid session returns the current user; without a session returns 401
  • Google OAuth round-trip completes and results in a session (manual browser test)
  • A user who registers via email then signs in via Google gets the same user record, not a duplicate

Phase 4: Habits and Check-ins API

This phase implements the core product: creating and managing habits, recording completions, and computing streaks on read. All business logic for recurrence, streak calculation, and note-keeping lives here. The ADD specifies streak calculation walks backwards from today through consecutive scheduled-and-completed days — that algorithm is implemented exactly as described.

Contracts

server/habits/validation.ts

Exports Zod schemas:

  • createHabitSchema — { name: string (min 1, trimmed), category: string | null, is_public: boolean, recurrence_days: number[] (each 0–6, non-empty) }
  • updateHabitSchema — same fields, all optional (partial)
  • createCheckInSchema — { note: string | null }

server/habits/service.ts

Exports pure business logic functions — no Express types, no HTTP concerns. All functions are async and return plain objects or throw an AppError subclass.

  • normalizeHabitName(name: string): string

    • Lowercases and trims the input
    • Returns the normalized string
    • Used server-side only; never accepts client input for this field
  • createHabit(userId: string, data: CreateHabitInput): Promise<Habit>

    • CreateHabitInput: { name: string, category: string | null, is_public: boolean, recurrence_days: number[] }
    • Computes name_normalized via normalizeHabitName
    • Inserts the habit and returns the full Habit row
  • updateHabit(habitId: string, userId: string, data: Partial<CreateHabitInput>): Promise<Habit>

    • Verifies ownership (throws NotFoundError if the habit doesn't exist or doesn't belong to userId)
    • If name is in data, recomputes name_normalized
    • Updates only the provided fields; returns the updated Habit
  • archiveHabit(habitId: string, userId: string): Promise<void>

    • Verifies ownership; sets archived_at to now; does not delete the row
  • getHabitsForUser(userId: string): Promise<Habit[]>

    • Returns all non-archived habits for the user (where archived_at IS NULL)
  • getHabitById(habitId: string, userId: string): Promise<Habit>

    • Returns the habit if it exists and belongs to userId; throws NotFoundError otherwise
    • Also returns archived habits (callers that want only active habits filter themselves, but this function is the ownership check used by check-in and reminder routes)
  • createCheckIn(habitId: string, userId: string, data: { note: string | null }): Promise<CheckIn>

    • Verifies the habit exists and belongs to userId (via getHabitById)
    • Sets checked_at to the current server timestamp
    • Inserts and returns the CheckIn row
  • getCheckInsForHabit(habitId: string, userId: string): Promise<CheckIn[]>

    • Verifies ownership; returns all check-ins for the habit, ordered by checked_at DESC
  • calculateStreak(habitId: string, recurrenceDays: number[], userTimezone: string): Promise<number>

    • Fetches check-in dates for the habit from the database, ordered descending
    • Converts checked_at timestamps to dates in userTimezone
    • Starting from today (in userTimezone), walks backwards day by day
    • For each day: if it's in recurrenceDays, checks whether at least one check-in exists for that date; if yes, continues; if no, stops
    • Days not in recurrenceDays are skipped (do not break the streak)
    • Returns the count of consecutive due-and-completed days
  • getHabitWithStreak(habitId: string, userId: string, userTimezone: string): Promise<HabitWithStreak>

    • HabitWithStreak: Habit & { streak: number }
    • Calls getHabitById then calculateStreak; returns the combined shape
  • getHabitsWithStreaks(userId: string, userTimezone: string): Promise<HabitWithStreak[]>

    • Calls getHabitsForUser then calculateStreak for each result
    • Returns the array of HabitWithStreak

server/habits/routes.ts

Exports an Express Router mounted at /habits. All routes require requireAuth.

  • GET /habits → calls getHabitsWithStreaks(req.user.id, req.user.timezone); returns { habits: HabitWithStreak[] }
  • POST /habits → validates with createHabitSchema; calls createHabit; returns { habit: Habit } with a 201 status
  • GET /habits/:habitId → calls getHabitWithStreak; returns { habit: HabitWithStreak }
  • PATCH /habits/:habitId → validates with updateHabitSchema; calls updateHabit; returns { habit: Habit }
  • DELETE /habits/:habitId → calls archiveHabit; returns { success: true }
  • POST /habits/:habitId/checkins → validates with createCheckInSchema; calls createCheckIn; returns { checkIn: CheckIn } with 201
  • GET /habits/:habitId/checkins → calls getCheckInsForHabit; returns { checkIns: CheckIn[] }

Error handling contract for database operations: if a Drizzle query throws due to a connection failure or unexpected database error, the Express error handler in Phase 2 catches it, logs it with route path and user ID, and returns a generic server error response. This contract applies to all database operations in this phase and all subsequent phases — later phases inherit it without restatement.

Deliverables:

  • POST /habits with valid data creates a habit; the stored name_normalized is lowercase and trimmed regardless of what the client sent
  • GET /habits returns habits with correct streak counts for the authenticated user's timezone
  • A habit with recurrence_days: [1, 3] (Monday, Wednesday) and check-ins on the last three consecutive Mon/Wed dates has a streak of 3; a missed Monday shows a streak of 0
  • DELETE /habits/:habitId sets archived_at without deleting the row; the habit no longer appears in GET /habits
  • POST /habits/:id/checkins from a user who doesn't own the habit returns 404

Phase 5: Reminders API

This phase adds the reminder configuration endpoints. Users can create, list, update, and delete reminder times for a habit. The scheduler in Phase 7 will consume the same data model established here.

Contracts

server/reminders/validation.ts

Exports Zod schemas:

  • createReminderSchema — { remind_at_time: string } where the string matches HH:MM in 24-hour format (regex: /^([01]\d|2[0-3]):[0-5]\d$/)
  • updateReminderSchema — same shape

server/reminders/service.ts

Exports:

  • createReminder(habitId: string, userId: string, remindAtTime: string): Promise<Reminder>

    • Verifies the habit exists and belongs to userId by calling getHabitById from the habits service
    • Inserts and returns the Reminder row
  • getRemindersForHabit(habitId: string, userId: string): Promise<Reminder[]>

    • Verifies ownership via getHabitById
    • Returns all reminders for the habit
  • updateReminder(reminderId: string, userId: string, remindAtTime: string): Promise<Reminder>

    • Looks up the reminder; verifies user_id matches; throws NotFoundError if not
    • Updates remind_at_time; returns the updated row
  • deleteReminder(reminderId: string, userId: string): Promise<void>

    • Looks up the reminder; verifies user_id matches; throws NotFoundError if not
    • Deletes the row
  • getDueReminders(currentMinuteUtc: Date): Promise<DueReminder[]>

    • Used exclusively by the scheduler in Phase 7
    • DueReminder: { reminderId: string, userId: string, habitId: string, habitName: string, userEmail: string, userTimezone: string, remindAtTime: string }
    • Queries reminders joined to users and habits where the habit is not archived
    • Fetches all active reminders with their user's timezone and email; the scheduler (not this function) decides which ones are due in the current minute
    • Returns the full list; the scheduler filters by converting each remind_at_time to UTC using the user's timezone and comparing to currentMinuteUtc

server/reminders/routes.ts

Exports an Express Router mounted at /habits/:habitId/reminders. All routes require requireAuth.

  • GET /habits/:habitId/reminders → calls getRemindersForHabit; returns { reminders: Reminder[] }
  • POST /habits/:habitId/reminders → validates with createReminderSchema; calls createReminder; returns { reminder: Reminder } with 201
  • PATCH /habits/:habitId/reminders/:reminderId → validates with updateReminderSchema; calls updateReminder; returns { reminder: Reminder }
  • DELETE /habits/:habitId/reminders/:reminderId → calls deleteReminder; returns { success: true }

Deliverables:

  • POST /habits/:habitId/reminders with a valid time creates a reminder; attempts from non-owners return 404
  • GET /habits/:habitId/reminders returns all reminders for that habit
  • DELETE /habits/:habitId/reminders/:reminderId from a non-owner returns 404
  • getDueReminders called with the current UTC time returns a populated array when test reminders exist in the database

Phase 6: Social Features — Partnerships, Discovery, and Leaderboards

This phase implements the full social layer: accountability partner invitations, public habit discovery (follower counts by normalized name), and leaderboard queries. The invitation flow includes the email send to the invitee; if that send fails, no database record is created.

Contracts

server/email/client.ts

The single Resend wrapper used by all email-sending code in the application. Later phases (including the scheduler) import from here.

  • sendEmail(params: EmailParams): Promise<void>
    • EmailParams: { to: string, subject: string, html: string }
    • Uses EMAIL_FROM from the environment as the sender address
    • On success, returns undefined
    • On any failure (network error, API error, invalid recipient), throws ExternalServiceError with a message describing the failure; never leaks the raw SDK error to callers

Error handling contract for email operations: sendEmail is the sole point of failure handling for the Resend SDK. Any caller that catches ExternalServiceError from sendEmail decides what to do next (the invitation route returns it to the client; the scheduler logs and continues). All subsequent email calls in this phase and Phase 7 use this contract.

server/email/templates.ts

Exports functions that return HTML strings. No external template engine.

  • invitationEmailTemplate(params: { inviterEmail: string, appUrl: string }): string
    • Returns an HTML string for the partnership invitation email
  • reminderEmailTemplate(params: { habitName: string, appUrl: string }): string
    • Returns an HTML string for the habit reminder email
    • Used by the scheduler in Phase 7

server/social/service.ts

Exports:

  • sendPartnerInvite(requesterId: string, addresseeEmail: string): Promise<AccountabilityPartner>

    • Looks up the addressee user by email; throws NotFoundError if no account exists with that email
    • Checks whether a partnership record already exists between requester and addressee (in either direction); throws ConflictError if so
    • Calls sendEmail with the invitation template; if sendEmail throws ExternalServiceError, re-throws it — no database record is created
    • If the email succeeds, inserts the AccountabilityPartner row with status: 'pending'
    • Returns the new row
  • respondToInvite(partnershipId: string, addresseeId: string, response: 'accepted' | 'rejected'): Promise<AccountabilityPartner>

    • Looks up the partnership; throws NotFoundError if not found or if addressee_id !== addresseeId
    • Throws ConflictError if the current status is not 'pending'
    • Updates status to the given response; returns the updated row
  • getPartnerships(userId: string): Promise<PartnershipWithUser[]>

    • PartnershipWithUser: AccountabilityPartner & { partnerEmail: string, partnerTimezone: string }
    • Returns all accepted partnerships where the user is either requester or addressee
    • Joins to the users table to include the partner's email and timezone
  • getPartnerHabits(viewerUserId: string, partnerUserId: string): Promise<HabitWithStreak[]>

    • Verifies an accepted partnership exists between viewer and partner (in either direction); throws NotFoundError if not
    • Returns only the partner's public habits (is_public = true, archived_at IS NULL)
    • Includes streak for each habit calculated using the partner's timezone
    • Reuses calculateStreak from the habits service
  • getPublicHabitCount(nameNormalized: string, category: string | null): Promise<number>

    • Counts distinct users tracking a public habit with the given name_normalized
    • If category is provided, adds it as a filter condition (category-scoped matching per ADD Risk 3 mitigation)
    • Returns the count as a number
  • getLeaderboard(category: string | null, limit: number): Promise<LeaderboardEntry[]>

    • LeaderboardEntry: { userId: string, email: string, habitName: string, habitId: string, streak: number }
    • Fetches all public, non-archived habits (filtered by category if provided)
    • Computes streak for each using the habit owner's timezone
    • Sorts by streak descending; returns the top limit entries (maximum 100)

server/social/routes.ts

Exports an Express Router mounted at /social. All routes require requireAuth.

  • POST /social/partners/invite — body: { email: string }; calls sendPartnerInvite(req.user.id, email); returns { partnership: AccountabilityPartner } with 201
  • PATCH /social/partners/:partnershipId — body: { response: 'accepted' | 'rejected' }; calls respondToInvite; returns { partnership: AccountabilityPartner }
  • GET /social/partners — calls getPartnerships(req.user.id); returns { partnerships: PartnershipWithUser[] }
  • GET /social/partners/:partnerUserId/habits — calls getPartnerHabits(req.user.id, partnerUserId); returns { habits: HabitWithStreak[] }
  • GET /social/discover — query param: name (required), category (optional); calls getPublicHabitCount; returns { count: number }
  • GET /social/leaderboard — query param: category (optional), limit (optional, default 20, max 100); calls getLeaderboard; returns { leaderboard: LeaderboardEntry[] }

Deliverables:

  • POST /social/partners/invite with a valid email sends an email via Resend and creates a partnership record; if called a second time for the same pair, returns 409
  • POST /social/partners/invite when Resend throws returns an error response and no database record is created (verify by checking the accountability_partners table)
  • PATCH /social/partners/:id from the addressee with { response: 'accepted' } updates the status; the same call from the requester returns 404
  • GET /social/partners/:partnerUserId/habits with no accepted partnership returns 404; with an accepted partnership returns only public habits with streak counts
  • GET /social/leaderboard returns entries sorted by streak descending

Phase 7: Background Scheduler and Email Reminders

This phase wires the node-cron scheduler into the Express process and implements the reminder-sending logic. The scheduler runs once per minute, calls getDueReminders from Phase 5, filters to reminders due in the current minute window, and sends each via sendEmail from Phase 6. Failures are logged and skipped — no retry, no queue.

Contracts

server/scheduler/index.ts

Exports:

  • startScheduler(): void

    • Called once from server/index.ts at startup after the Express server starts listening
    • Registers a node-cron job that fires every minute
    • Each tick calls runReminderTick() and catches any unhandled error from it, logging to stdout without crashing the process
  • runReminderTick(): Promise<void> (also exported for testability)

    • Gets the current UTC time (start of the current minute, seconds and milliseconds zeroed)
    • Calls getDueReminders(currentMinuteUtc) to get all active reminders
    • For each DueReminder, converts remind_at_time (in userTimezone) to a UTC time for the current day
    • Compares to currentMinuteUtc; if the hour and minute match, proceeds
    • Checks whether the habit was due today (the current day in userTimezone is in recurrence_days)
    • Checks whether at least one check-in exists for the habit today (in the user's timezone) — if yes, skips (already completed)
    • If due and not completed, calls sendEmail with the reminder template from server/email/templates.ts
    • If sendEmail throws ExternalServiceError: logs { event: 'reminder_send_failed', userId, habitId, error: message } to stdout and continues to the next reminder
    • Logs { event: 'reminder_sent', userId, habitId } to stdout on success

The check-in lookup in runReminderTick uses a targeted query: SELECT 1 FROM check_ins WHERE habit_id = $1 AND user_id = $2 AND checked_at >= $3 AND checked_at < $4 LIMIT 1, where $3 and $4 are the start and end of the current day in the user's timezone, expressed as UTC timestamps. This query is not exposed as a service function — it lives inline in the scheduler.

Deliverables:

  • Server startup logs confirm the scheduler has registered (e.g., a single { event: 'scheduler_started' } log line)
  • A reminder configured for the current minute fires and an email appears in the Resend dashboard's sent log
  • A reminder for a habit already checked in today does not trigger a send (verified via sent log)
  • A simulated Resend failure (temporarily invalid API key) causes the tick to log reminder_send_failed and continue without crashing the server

Phase 8: User Settings API

This phase adds the user-facing settings endpoints: updating timezone and email, and deleting the account. Account deletion cascades via the database's FK constraints — no application-layer cleanup loop is needed.

Contracts

server/users/validation.ts

Exports Zod schemas:

  • updateUserSchema — { timezone: string (optional), email: string email (optional) } — at least one field must be present (use .refine to enforce this)
  • deleteAccountSchema — { confirmEmail: string } — the user must supply their own email to confirm deletion

server/users/service.ts

Exports:

  • updateUser(userId: string, data: { timezone?: string, email?: string }): Promise<PublicUser>

    • If email is provided, checks that no other user owns that email (throws ConflictError if taken)
    • Updates the user row; returns the updated PublicUser shape ({ id, email, timezone })
  • deleteUser(userId: string, confirmEmail: string): Promise<void>

    • Looks up the user; throws NotFoundError if not found
    • Compares confirmEmail (case-insensitive) to the user's stored email; throws ValidationError if it doesn't match
    • Deletes the user row; the cascade on the database schema (Phase 1) removes all associated habits, check-ins, reminders, and partnerships

server/users/routes.ts

Exports an Express Router mounted at /users. All routes require requireAuth.

  • PATCH /users/me — validates with updateUserSchema; calls updateUser(req.user.id, data); returns { user: PublicUser }
  • DELETE /users/me — validates with deleteAccountSchema; calls deleteUser(req.user.id, confirmEmail); destroys the session; returns { success: true }

Deliverables:

  • PATCH /users/me with { timezone: 'America/New_York' } updates the user's timezone; subsequent streak calculations on GET /habits reflect the new timezone
  • PATCH /users/me with an email already belonging to another account returns 409
  • DELETE /users/me with the correct email deletes the user and all their data; the session is destroyed; the same session cookie returns 401 on the next request
  • DELETE /users/me with the wrong confirmation email returns 400

Phase 9: React Frontend

This phase builds the complete React SPA. It consumes every API endpoint defined in Phases 3–8. The frontend is compiled by Vite and served statically by Express from /public. All client-side routing uses React Router. Zod schemas defined in the backend validation files are reused on the frontend for form validation — the same schema, imported directly, not duplicated.

Contracts

client/src/lib/api.ts

A thin, typed fetch wrapper. Every component and hook uses this — no component calls fetch directly.

  • apiFetch<T>(path: string, options?: RequestInit): Promise<T>
    • Prepends / to the path if not already present
    • Sets credentials: 'include' on every request (required for session cookies)
    • On a non-OK response, reads the response body and throws an Error with the error field from { error: string }
    • On a network failure, throws with a user-friendly message
    • Returns the parsed JSON as T

client/src/lib/auth.tsx

Exports:

  • AuthProvider — React context provider; fetches GET /auth/me on mount to hydrate the current user
  • useAuth(): { user: PublicUser | null, isLoading: boolean, setUser: (u: PublicUser | null) => void }
    • PublicUser: { id: string, email: string, timezone: string } — same shape as the backend's PublicUser

Page and component structure

The file tree below is the authoritative module list for the frontend. No pages or components are added beyond this list.

client/src/
  pages/
    LoginPage.tsx         — email/password login form + Google OAuth button
    RegisterPage.tsx      — registration form
    DashboardPage.tsx     — lists the user's habits with streak counts; today's completion status
    HabitDetailPage.tsx   — single habit view: check-in history, reminders, notes
    HabitFormPage.tsx     — create and edit habit (shared form)
    SocialPage.tsx        — partner list, invite form, leaderboard, public discovery
    SettingsPage.tsx      — timezone, email update, account deletion
  components/
    ProtectedRoute.tsx    — wraps routes requiring auth; redirects to /login if no session
    HabitCard.tsx         — displays a single habit with its streak and today's check-in button
    CheckInButton.tsx     — logs a check-in for today; accepts an optional note
    StreakBadge.tsx        — displays current streak count with a visual indicator
    PartnerCard.tsx       — displays a partner with a link to their public habits
    LeaderboardTable.tsx  — renders the leaderboard entries
    ReminderForm.tsx      — add/edit/delete reminder times for a habit
  lib/
    api.ts
    auth.tsx

Routing table (React Router)

All routes are defined in client/src/main.tsx:

  • /login → LoginPage
  • /register → RegisterPage
  • / → DashboardPage (protected)
  • /habits/new → HabitFormPage (protected)
  • /habits/:habitId → HabitDetailPage (protected)
  • /habits/:habitId/edit → HabitFormPage (protected)
  • /social → SocialPage (protected)
  • /settings → SettingsPage (protected)
  • * → redirect to /

Form validation

Forms in LoginPage, RegisterPage, HabitFormPage, and SettingsPage validate with the same Zod schemas used in the backend (registerSchema, createHabitSchema, updateUserSchema). These schemas are imported from server/auth/validation.ts and server/habits/validation.ts — not duplicated. This requires those schema files to be importable from the client bundle (they must not import any Node.js-only modules).

Deliverables:

  • The Vite build completes without errors and places the bundle in /public
  • Navigating to the app root when unauthenticated redirects to /login
  • Registering a new account and logging in lands on the Dashboard showing zero habits
  • Creating a habit with recurrence days, navigating to the dashboard, and clicking the check-in button records a check-in and increments the displayed streak
  • The leaderboard on the Social page displays entries when public habits with check-ins exist
  • The settings page timezone change is reflected in streak display after saving

Prompt Pack

Prompt Pack

This Prompt Pack provides a complete 10-phase step-by-step instruction sequence for Replit to scaffold Strata, a production social habit tracker. Each prompt targets an isolated product phase—covering project foundation, database schema, background scheduling, social logic, and email integration.

Strata runs on a modern serverless tech stack comprising React with Vite, Node.js with Express, PostgreSQL (Neon), Drizzle ORM, and Resend for transactional email.


Prompt 1

You'll end up with a complete project skeleton — all the folders, configuration files, and database table definitions — but no running server yet. The database schema covers every table the app will ever need, so you won't have to change it later. Once this prompt is done, you'll run two commands in the Replit Shell to create the tables in your database.


Paste everything below into your AI coding tool:

We are building a full-stack Strata app on Replit. The stack is Node.js with Express on the backend, React with Vite on the frontend, PostgreSQL via Replit's managed database, and Drizzle ORM for database access. Nothing exists yet — this prompt sets up the entire project scaffold and database schema.

TypeScript configuration

Configure TypeScript for the project using CommonJS modules throughout (this ensures Express and all Node.js tooling work without ESM compatibility issues on Replit). The TypeScript config must apply to both the server/ and db/ directories. The client/ directory will use a separate Vite-managed TypeScript config added in a later prompt.

package.json scripts

Define the following scripts — do not fill in version numbers, just use the latest compatible versions for all dependencies:

  • "build" — runs vite build to compile the React frontend
  • "start" — runs the compiled server entry point (the output of the TypeScript compiler or tsx, whichever approach is idiomatic for Replit's Node.js environment)
  • "dev" — runs both the Express server and Vite simultaneously using concurrently "tsx watch server/index.ts" "vite" for fast iteration.
  • "db:generate" — runs drizzle-kit generate to produce migration SQL from the schema
  • "db:migrate" — runs drizzle-kit migrate to apply pending migrations to the database

Install all required dependencies for the full project now: Express, Drizzle ORM and Drizzle Kit, the drizzle-orm/node-postgres driver, Passport.js with the local and Google strategies, bcrypt, express-session, connect-pg-simple, node-cron, Zod, Resend SDK, Helmet, the pg package, concurrently, and the React + Vite + React Router stack for the frontend. Include all necessary TypeScript type packages.

drizzle.config.ts (project root)

Drizzle Kit configuration file. Points to db/schema.ts as the schema source and db/migrations/ as the migration output directory. Reads DATABASE_URL from the environment.

db/schema.ts

Define the complete Drizzle schema for all six tables. Every subsequent module imports its types from this single file — no table shape is defined anywhere else.

Tables and their columns:

  • users: id (UUID, primary key, default generated), email (text, unique, not null), password_hash (text, nullable), google_id (text, unique, nullable), timezone (text, not null, default 'UTC'), created_at (timestamp with time zone, not null, default now)

  • habits: id (UUID, primary key), user_id (UUID, foreign key → users, not null), name (text, not null), name_normalized (text, not null — add an index on this column), category (text, nullable), is_public (boolean, not null, default false), recurrence_days (integer array, not null), archived_at (timestamp with time zone, nullable)

  • check_ins: id (UUID, primary key), habit_id (UUID, foreign key → habits, not null), user_id (UUID, foreign key → users, not null), checked_at (timestamp with time zone, not null), note (text, nullable). Add a composite index on (habit_id, checked_at DESC) — this is required for streak calculation performance.

  • reminders: id (UUID, primary key), habit_id (UUID, foreign key → habits, not null — cascade delete when the habit is deleted), user_id (UUID, foreign key → users, not null), remind_at_time (time, not null)

  • accountability_partners: id (UUID, primary key), requester_id (UUID, foreign key → users, not null), addressee_id (UUID, foreign key → users, not null), status (text, not null — add a check constraint enforcing the value is one of 'pending', 'accepted', 'rejected'), created_at (timestamp with time zone, not null, default now). Add a unique constraint on (requester_id, addressee_id).

  • sessions: the shape required by connect-pg-simple: sid (text, primary key), sess (jsonb, not null), expire (timestamp with time zone, not null). Add an index on expire.

Export the following TypeScript types inferred by Drizzle from the schema — these are the shapes every other module uses:

  • User, NewUser (select and insert types for users)
  • Habit, NewHabit (select and insert types for habits)
  • CheckIn, NewCheckIn (select and insert types for check_ins)
  • Reminder, NewReminder (select and insert types for reminders)
  • AccountabilityPartner, NewAccountabilityPartner (select and insert types for accountability_partners)

db/index.ts

Creates and exports a single db instance — the Drizzle client connected to DATABASE_URL. Uses the drizzle-orm/node-postgres driver along with the standard pg package. Every module in the project that needs database access imports db from this file. No second connection is created anywhere.

Export:

  • db — the Drizzle database client parameterized over the full schema

db/migrations/

This directory is where Drizzle Kit writes generated SQL migration files. Create it (it can be empty at this point — the db:generate script populates it).

Do not build yet: the Express server, any routes, any authentication logic, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • In the Replit Shell, run npm run db:generate. It should complete without errors and create at least one SQL file inside db/migrations/.
  • Then run npm run db:migrate. It should apply the migration without errors.
  • Ask your tool to confirm all six tables were created in the database and that no TypeScript errors exist in db/schema.ts or db/index.ts.
  • If something is wrong: paste the exact error message back to the agent and ask it to fix the schema or configuration before continuing.

Prompt 2

Run this after Prompt 1 is complete.

You'll end up with a running web server that responds to a health check and enforces security headers and CORS. No routes or login functionality yet — just the server foundation every later feature will build on. When this prompt is done, you'll be able to open your Repl's URL and see a response.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompt 1 established the database schema in db/schema.ts and db/index.ts. This prompt stands up the Express server with all middleware in place and a health check endpoint.

server/errors.ts

Defines the application's error class hierarchy. All phases use these — no raw database errors or SDK errors are ever thrown across a module boundary.

Export:

  • AppError — base class; constructor takes message: string and statusCode: number; exposes both as public properties
  • NotFoundError extends AppError — fixed status 404; used when a resource doesn't exist or the requesting user isn't authorized to know it exists
  • UnauthorizedError extends AppError — fixed status 401; used when no valid session exists
  • ValidationError extends AppError — fixed status 400; used when Zod rejects input
  • ConflictError extends AppError — fixed status 409; used for constraint violations such as duplicate partnership invites
  • ExternalServiceError extends AppError — fixed status 502; used when Resend or Google OAuth fails in a way the caller should know about

server/middleware/errorHandler.ts

Exports a single Express error-handling middleware (four-argument form):

  • errorHandler(err, req, res, next): void
    • Logs the error to stdout including the route path and req.user?.id if a session user is present. The log must never include a stack trace, internal database error detail, or raw SDK error text.
    • If err is an instance of AppError, responds with err.statusCode and { error: err.message }
    • For any other error type, responds with a generic server error status and { error: 'An unexpected error occurred' }

server/router.ts

A barrel module that imports all domain route modules and mounts them under their path prefixes using an Express Router. In this prompt it is empty — it exports an Express Router with no routes mounted. Later prompts add their route modules here without modifying server/index.ts.

Export:

  • router — an Express Router instance (no routes mounted yet)

server/index.ts

The application entry point. Constructs and starts the Express app. Middleware must be mounted in this exact order:

  1. Helmet (default configuration)
  2. CORS — allowed origin is APP_URL from the environment; credentials allowed; no wildcard
  3. JSON body parser
  4. express-session with connect-pg-simple as the store:
    • Session secret from SESSION_SECRET environment variable
    • Cookie: httpOnly: true, sameSite: 'strict', secure: true
    • Session max age: 30 days
    • The connect-pg-simple store uses the same DATABASE_URL the rest of the app uses; it does not create a second Drizzle instance — it connects via pg directly as connect-pg-simple expects
  5. passport.initialize() and passport.session() — Passport itself is configured in the next prompt; mount the middleware stubs here
  6. Static file serving from the public/ directory at the project root (this serves the compiled React bundle added in Prompt 9)
  7. Mount router from server/router.ts at /
  8. Mount errorHandler from server/middleware/errorHandler.ts as the final middleware

Additionally, define a GET /health route directly in server/index.ts (before the router) that returns { status: 'ok' }.

When a request reaches an undefined route (and the router has no match), the error handler must return { error: 'Not found' } rather than Express's default HTML response. Ensure this is handled — either by a catch-all route in server/router.ts or an explicit 404 handler before the error handler.

Exports nothing — this is the process entry point. It starts the server listening when executed.

Do not build yet: authentication strategies, any domain routes, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • In the Replit Shell, run npm run dev. The server should start without errors.
  • Open your Repl's public URL and add /health to the end. You should see {"status":"ok"} in the browser.
  • Open any other path (e.g. /does-not-exist). You should see {"error":"Not found"} — not an HTML page.
  • If something is wrong: paste the error from the Shell or browser back to the agent and ask it to fix it before continuing.

Prompt 3

Run this after Prompt 2 is complete.

You'll end up with a working login and registration system — users can create accounts with email and password, sign in with Google, and log out. The requireAuth middleware that protects every route in later prompts is also created here.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1 and 2 established the database schema, the db client, and the Express server with middleware. This prompt implements the full authentication system: Passport.js local and Google OAuth strategies, session handling, and auth routes.

server/auth/validation.ts

Exports Zod schemas used in the auth routes and reused by the frontend in Prompt 9. These files must not import any Node.js-only modules so they can be bundled by Vite for the client.

Export:

  • registerSchema — object with email (Zod email string) and password (string, minimum 8 characters)
  • loginSchema — same shape as registerSchema

server/middleware/requireAuth.ts

Exports a single Express middleware:

  • requireAuth(req, res, next): void
    • If req.isAuthenticated() returns true, calls next()
    • Otherwise throws UnauthorizedError (imported from server/errors.ts)

server/auth/passport.ts

Configures Passport strategies and session serialization. Called once from server/index.ts for its side effects. Exports nothing.

LocalStrategy behavior (strategy name: 'local'):

  1. Receives email and password from the request body
  2. Looks up the user in the users table by email (case-insensitive comparison)
  3. If no user is found, calls done with the message 'Invalid email or password' — do not distinguish between "no account" and "wrong password"
  4. Compares the submitted password against the stored password_hash using bcrypt
  5. If the hash does not match, calls done with the same message 'Invalid email or password'
  6. On success, passes the full User row to done

GoogleStrategy behavior (using GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET from the environment; callback URL constructed from APP_URL as ${APP_URL}/auth/google/callback):

  1. Receives the Google profile's email and the profile's ID field as google_id
  2. Looks up an existing user by google_id first; if found, passes that user to done
  3. If not found by google_id, looks up by email (case-insensitive)
  4. If found by email, updates that user's google_id field to link the accounts, then passes the updated user to done
  5. If neither lookup finds a match, creates a new User row with password_hash: null and google_id set; passes the new user to done
  6. On any database error, passes the error to done

Session serialization:

  • serializeUser: stores user.id (the UUID string) in the session
  • deserializeUser: looks up the full User row by that ID; if no user is found, passes null (Passport treats this as a logged-out session)

After defining strategies and serialization, call configurePassport() — or equivalent initialization — from server/index.ts so Passport is configured before the first request arrives.

server/auth/routes.ts

Exports an Express Router. This router is imported and mounted at /auth in server/router.ts.

The PublicUser shape used in all responses below: { id: string, email: string, timezone: string }. Never include password_hash or google_id in any response.

Routes:

  • POST /register

    • Validates the request body with registerSchema; on failure throws ValidationError with the Zod error details
    • Checks for an existing user with the same email (case-insensitive); if found throws ConflictError with the message 'An account with this email already exists'
    • Hashes the password with bcrypt at 12 rounds
    • Inserts a new User row
    • Establishes a session (calls req.login)
    • Responds with status 201 and { user: PublicUser }
  • POST /login

    • Validates the request body with loginSchema; on failure throws ValidationError
    • Delegates to Passport LocalStrategy via passport.authenticate('local', ...)
    • On success: responds with { user: PublicUser }
    • On failure: throws UnauthorizedError with the message returned by the strategy ('Invalid email or password')
  • GET /google

    • Initiates Google OAuth redirect via Passport; requests email and profile scopes
  • GET /google/callback

    • OAuth callback handler
    • On success: redirect to /
    • On failure: redirect to /login?error=oauth_failed
  • POST /logout

    • Destroys the session and clears the session cookie
    • Responds with { success: true }
  • GET /me

    • Protected by requireAuth
    • Responds with { user: PublicUser } for the currently authenticated user

Mount this router in server/router.ts at /auth.

Do not build yet: habit routes, check-in routes, reminder routes, social routes, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • Use your Repl's web preview. Submit the registration form (or use a tool like the browser's network tab) to POST /auth/register with a valid email and password — you should receive { user: { id, email, timezone } } with status 201.
  • POST /auth/login with the same credentials should return the same shape.
  • POST /auth/login with a wrong password should return a 401 with { error: 'Invalid email or password' }.
  • GET /auth/me immediately after login should return your user; in a fresh browser tab (no session) it should return 401.
  • If something is wrong: paste the error response back to the agent and ask it to fix the auth logic before continuing.

Prompt 4

Run this after Prompt 3 is complete.

You'll end up with the core of the app: users can create habits, log daily completions, and see their current streak count. Streak calculation is done on every read — it walks backwards through your check-in history and counts consecutive days you completed the habit, skipping days it wasn't scheduled.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–3 established the database schema, Express server, and authentication. This prompt implements habits and check-ins: the CRUD endpoints, streak calculation, and check-in recording.

server/habits/validation.ts

Exports Zod schemas. These files must not import any Node.js-only modules so they can be bundled by Vite for the frontend in Prompt 9.

Export:

  • createHabitSchema — object: name (string, minimum 1 character, trimmed), category (string or null, optional), is_public (boolean), recurrence_days (array of integers each between 0 and 6 inclusive, minimum 1 element)
  • updateHabitSchema — same fields as createHabitSchema, all optional (partial), with the same individual field constraints
  • createCheckInSchema — object: note (string or null, optional)

server/habits/service.ts

Exports pure async business logic functions. No Express types. All functions throw an AppError subclass on failure — they never return error-shaped objects.

  • normalizeHabitName(name: string): string

    • Lowercases and trims the input string
    • Returns the normalized result
    • This function is called server-side only; the name_normalized field is never accepted from the client
  • createHabit(userId: string, data: CreateHabitInput): Promise<Habit>

    • CreateHabitInput: { name: string, category: string | null, is_public: boolean, recurrence_days: number[] }
    • Computes name_normalized by calling normalizeHabitName(data.name)
    • Inserts the habit row and returns the full Habit record
  • updateHabit(habitId: string, userId: string, data: Partial<CreateHabitInput>): Promise<Habit>

    • Verifies that a habit with habitId exists and has user_id === userId; throws NotFoundError if not
    • If data.name is present, recomputes name_normalized
    • Updates only the fields provided in data
    • Returns the updated Habit record
  • archiveHabit(habitId: string, userId: string): Promise<void>

    • Verifies ownership (same check as updateHabit); throws NotFoundError if not
    • Sets archived_at to the current timestamp; does not delete the row
  • getHabitsForUser(userId: string): Promise<Habit[]>

    • Returns all habits where user_id === userId and archived_at IS NULL
  • getHabitById(habitId: string, userId: string): Promise<Habit>

    • Returns the habit if it exists and user_id === userId; throws NotFoundError otherwise
    • Returns archived habits as well — this function is the canonical ownership check used by check-in and reminder routes
  • createCheckIn(habitId: string, userId: string, data: { note: string | null }): Promise<CheckIn>

    • Verifies the habit exists and belongs to userId by calling getHabitById
    • Sets checked_at to the current server UTC timestamp
    • Inserts and returns the CheckIn row
  • getCheckInsForHabit(habitId: string, userId: string): Promise<CheckIn[]>

    • Verifies ownership via getHabitById
    • Returns all check-ins for the habit ordered by checked_at DESC
  • calculateStreak(habitId: string, recurrenceDays: number[], userTimezone: string): Promise<number>

    • Fetches all checked_at timestamps for the habit from check_ins, ordered descending
    • Converts each timestamp to a calendar date in userTimezone
    • Starting from today (the current date in userTimezone), walks backwards day by day:
      • If the day is in recurrenceDays: check whether at least one check-in date matches that day; if yes, increment the streak count and continue; if no, stop the walk
      • If the day is not in recurrenceDays: skip it without breaking or counting
    • Returns the final streak count as an integer
    • This function must be correct: a habit scheduled Monday and Wednesday with check-ins on the last three Mon/Wed dates has a streak of 3; a missed Monday breaks the streak to 0
  • getHabitWithStreak(habitId: string, userId: string, userTimezone: string): Promise<HabitWithStreak>

    • HabitWithStreak: the Habit type intersected with { streak: number }
    • Calls getHabitById then calculateStreak; returns the merged result
  • getHabitsWithStreaks(userId: string, userTimezone: string): Promise<HabitWithStreak[]>

    • Calls getHabitsForUser, then calls calculateStreak for each result
    • Returns the full array of HabitWithStreak

Export the HabitWithStreak type — it is consumed by the social service in Prompt 6.

server/habits/routes.ts

Exports an Express Router. All routes require requireAuth. Mount this router in server/router.ts at /habits.

  • GET /habits — calls getHabitsWithStreaks(req.user.id, req.user.timezone); responds with { habits: HabitWithStreak[] }
  • POST /habits — validates with createHabitSchema; calls createHabit; responds with status 201 and { habit: Habit }
  • GET /habits/:habitId — calls getHabitWithStreak(habitId, req.user.id, req.user.timezone); responds with { habit: HabitWithStreak }
  • PATCH /habits/:habitId — validates with updateHabitSchema; calls updateHabit; responds with { habit: Habit }
  • DELETE /habits/:habitId — calls archiveHabit; responds with { success: true }
  • POST /habits/:habitId/checkins — validates with createCheckInSchema; calls createCheckIn; responds with status 201 and { checkIn: CheckIn }
  • GET /habits/:habitId/checkins — calls getCheckInsForHabit; responds with { checkIns: CheckIn[] }

Validation errors from Zod must be caught at the route layer and thrown as ValidationError before they reach the error handler.

If a Drizzle query throws due to a connection failure or unexpected database error, the Express error handler (from Prompt 2) catches it, logs it with the route path and user ID, and returns a generic server error response. This applies to all database operations across this prompt and all future prompts — later prompts inherit this without restatement.

Do not build yet: reminder routes, social routes, the scheduler, user settings routes, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • POST /habits with { name: "Exercise", is_public: true, recurrence_days: [1, 3], category: "health" } should create a habit and return it. Check that name_normalized in the response is "exercise" (lowercase).
  • GET /habits should return the habit with a streak field (0 at this point since there are no check-ins).
  • POST /habits/:habitId/checkins should record a check-in and return it.
  • DELETE /habits/:habitId should return { success: true }; a subsequent GET /habits should no longer include that habit.
  • POST /habits/:habitId/checkins for a habit belonging to a different user should return 404.
  • If something is wrong: paste the error back to the agent and ask it to fix before continuing.

Prompt 5

Run this after Prompt 4 is complete.

You'll end up with reminder configuration endpoints — users can set one or more times per day for each habit to receive an email reminder. The scheduler in Prompt 7 will read these configurations to decide when to send emails.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–4 established the schema, server, auth, and habits. This prompt adds reminder configuration: the endpoints to create, read, update, and delete reminder times for habits, plus the data-fetching function the scheduler will use.

server/reminders/validation.ts

Exports Zod schemas:

  • createReminderSchema — object: remind_at_time (string matching the pattern for 24-hour time HH:MM, e.g. "14:30")
  • updateReminderSchema — same shape as createReminderSchema

server/reminders/service.ts

Exports async service functions. All throw AppError subclasses on failure.

  • createReminder(habitId: string, userId: string, remindAtTime: string): Promise<Reminder>

    • Verifies the habit exists and belongs to userId by calling getHabitById from server/habits/service.ts; throws NotFoundError if not
    • Inserts a new Reminder row with habit_id, user_id, and remind_at_time
    • Returns the inserted Reminder
  • getRemindersForHabit(habitId: string, userId: string): Promise<Reminder[]>

    • Verifies ownership via getHabitById
    • Returns all reminders for the habit
  • updateReminder(reminderId: string, userId: string, remindAtTime: string): Promise<Reminder>

    • Looks up the reminder by reminderId; throws NotFoundError if it doesn't exist or if its user_id does not match userId
    • Updates remind_at_time to the new value; returns the updated Reminder
  • deleteReminder(reminderId: string, userId: string): Promise<void>

    • Looks up the reminder by reminderId; throws NotFoundError if it doesn't exist or if its user_id does not match userId
    • Deletes the row
  • getDueReminders(currentMinuteUtc: Date): Promise<DueReminder[]>

    • Used exclusively by the scheduler in Prompt 7. This function does not filter by time — it returns all active reminders so the scheduler can apply its own time comparison logic.
    • Queries the reminders table joined to users (for email and timezone) and joined to habits (for name and archived_at)
    • Excludes reminders where the associated habit has archived_at IS NOT NULL
    • Returns all results as DueReminder[]

Export the DueReminder type:

type DueReminder = {
  reminderId: string;
  userId: string;
  habitId: string;
  habitName: string;
  userEmail: string;
  userTimezone: string;
  remindAtTime: string; // "HH:MM" in the user's local timezone
}

server/reminders/routes.ts

Exports an Express Router. All routes require requireAuth. Mount this router in server/router.ts at /habits (nested under habits so the full paths are /habits/:habitId/reminders/...).

  • GET /habits/:habitId/reminders — calls getRemindersForHabit(habitId, req.user.id); responds with { reminders: Reminder[] }
  • POST /habits/:habitId/reminders — validates with createReminderSchema; calls createReminder(habitId, req.user.id, remindAtTime); responds with status 201 and { reminder: Reminder }
  • PATCH /habits/:habitId/reminders/:reminderId — validates with updateReminderSchema; calls updateReminder(reminderId, req.user.id, remindAtTime); responds with { reminder: Reminder }
  • DELETE /habits/:habitId/reminders/:reminderId — calls deleteReminder(reminderId, req.user.id); responds with { success: true }

Validation errors from Zod must be caught at the route layer and thrown as ValidationError.

Do not build yet: social routes, the scheduler, user settings routes, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • POST /habits/:habitId/reminders with { "remind_at_time": "08:00" } should create a reminder and return it.
  • GET /habits/:habitId/reminders should return the reminder you just created.
  • DELETE /habits/:habitId/reminders/:reminderId from a user who does not own the reminder should return 404.
  • If something is wrong: paste the error back to the agent and ask it to fix before continuing.

Prompt 6

Run this after Prompt 5 is complete.

You'll end up with the social layer: users can invite friends as accountability partners, accept or reject invitations, view a partner's public habits and streaks, discover how many other users are tracking the same habit, and browse a leaderboard. Invitation emails are sent via Resend — if the email fails, no database record is created.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–5 established the schema, server, auth, habits, and reminders. This prompt adds the social layer: accountability partner invitations (including email delivery), public habit discovery, and leaderboards. It also creates the shared email client used here and by the scheduler in Prompt 7.

server/email/client.ts

The single Resend wrapper for the entire application. Both this prompt's invitation flow and the Prompt 7 scheduler import from here.

Export:

  • sendEmail(params: EmailParams): Promise<void>
    • EmailParams: { to: string, subject: string, html: string }
    • Reads EMAIL_FROM from the environment and uses it as the sender address
    • Uses the Resend Node.js SDK to send the email
    • On success, returns undefined
    • On any failure — network error, API error, or rejected recipient — catches the error, constructs an ExternalServiceError with a human-readable message (never leaking raw SDK error details), and throws it
    • This is the sole point where Resend SDK errors are handled; all callers receive ExternalServiceError and decide what to do next

server/email/templates.ts

Exports functions that return HTML strings. No external template engine.

  • invitationEmailTemplate(params: { inviterEmail: string, appUrl: string }): string

    • Returns an HTML email body for the accountability partner invitation, telling the recipient who invited them and providing a link to the app
  • reminderEmailTemplate(params: { habitName: string, appUrl: string }): string

    • Returns an HTML email body for a habit reminder, naming the habit and linking to the app
    • This template is imported by the scheduler in Prompt 7

server/social/service.ts

Exports async service functions. All throw AppError subclasses on failure.

  • sendPartnerInvite(requesterId: string, addresseeEmail: string): Promise<AccountabilityPartner>

    • Looks up the addressee by email (case-insensitive); throws NotFoundError with the message 'No account found with that email address' if not found
    • Checks for any existing accountability_partners row where (requester_id, addressee_id) matches in either direction; throws ConflictError with the message 'You already have a pending or active partnership with this user' if found
    • Calls sendEmail with the invitation template (using invitationEmailTemplate); if sendEmail throws ExternalServiceError, re-throws it immediately — no database record is written
    • If the email succeeds, inserts the AccountabilityPartner row with status: 'pending'
    • Returns the newly created row
  • respondToInvite(partnershipId: string, addresseeId: string, response: 'accepted' | 'rejected'): Promise<AccountabilityPartner>

    • Looks up the partnership by partnershipId; throws NotFoundError if not found or if addressee_id !== addresseeId (the requester cannot respond to their own invite)
    • Throws ConflictError with the message 'This invitation has already been responded to' if the current status is not 'pending'
    • Updates status to response; returns the updated row
  • getPartnerships(userId: string): Promise<PartnershipWithUser[]>

    • Returns all accountability_partners rows where status = 'accepted' and the user is either requester_id or addressee_id
    • Joins to users to include the partner's email and timezone
    • PartnershipWithUser: AccountabilityPartner & { partnerEmail: string, partnerTimezone: string }
  • getPartnerHabits(viewerUserId: string, partnerUserId: string): Promise<HabitWithStreak[]>

    • Verifies an accepted partnership exists between viewerUserId and partnerUserId (in either direction); throws NotFoundError if no accepted partnership exists
    • Returns only the partner's habits where is_public = true and archived_at IS NULL
    • Calculates streak for each habit using the partner's timezone, by calling calculateStreak from server/habits/service.ts
    • Returns HabitWithStreak[]
  • getPublicHabitCount(nameNormalized: string, category: string | null): Promise<number>

    • Counts the number of distinct users who have a public (is_public = true), non-archived habit with the given name_normalized
    • If category is not null, additionally filters by category
    • Returns the count as a number
  • getLeaderboard(category: string | null, limit: number): Promise<LeaderboardEntry[]>

    • LeaderboardEntry: { userId: string, email: string, habitName: string, habitId: string, streak: number }
    • Fetches all public (is_public = true), non-archived habits, filtered by category if provided
    • For each habit, looks up the owner's timezone and calls calculateStreak
    • Sorts results by streak descending
    • Returns the top limit entries; limit must be capped at 100 regardless of what the caller passes

server/social/routes.ts

Exports an Express Router. All routes require requireAuth. Mount this router in server/router.ts at /social.

  • POST /social/partners/invite — body: { email: string } (validate with Zod inline — email must be a valid email string); calls sendPartnerInvite(req.user.id, email); responds with status 201 and { partnership: AccountabilityPartner }
  • PATCH /social/partners/:partnershipId — body: { response: 'accepted' | 'rejected' } (validate with Zod inline); calls respondToInvite(partnershipId, req.user.id, response); responds with { partnership: AccountabilityPartner }
  • GET /social/partners — calls getPartnerships(req.user.id); responds with { partnerships: PartnershipWithUser[] }
  • GET /social/partners/:partnerUserId/habits — calls getPartnerHabits(req.user.id, partnerUserId); responds with { habits: HabitWithStreak[] }
  • GET /social/discover — query params: name (required string), category (optional string); calls getPublicHabitCount(nameNormalized, category ?? null) where nameNormalized is the result of normalizeHabitName(name) from server/habits/service.ts; responds with { count: number }
  • GET /social/leaderboard — query params: category (optional string), limit (optional integer, default 20, maximum 100); calls getLeaderboard(category ?? null, limit); responds with { leaderboard: LeaderboardEntry[] }

Validation errors from Zod must be caught at the route layer and thrown as ValidationError.

Do not build yet: the scheduler, user settings routes, or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • POST /social/partners/invite with a valid email address belonging to another account should return a 201 with a partnership record, and an invitation email should appear in the Resend dashboard's sent log.
  • Calling POST /social/partners/invite a second time for the same pair should return 409.
  • PATCH /social/partners/:partnershipId with { "response": "accepted" } from the addressee's session should update the status to accepted; the same call from the requester's session should return 404.
  • GET /social/leaderboard should return an array (possibly empty if no public habits with check-ins exist yet).
  • If something is wrong: paste the error back to the agent and ask it to fix before continuing.

Prompt 7

Run this after Prompt 6 is complete.

You'll end up with an automated email reminder system. Every minute, the app checks who has a reminder due and hasn't completed their habit yet, then sends them an email. You'll be able to confirm it works by checking the Resend sent log after the scheduled time passes.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–6 established the schema, server, auth, habits, reminders, social features, and the email client. This prompt wires the node-cron background scheduler into the Express process. The scheduler fires every minute, checks which reminders are due, and sends emails for habits that haven't been completed today.

server/scheduler/index.ts

Exports:

  • startScheduler(): void

    • Called once from server/index.ts after the server begins listening
    • Registers a node-cron job that fires every minute (cron expression * * * * *)
    • On each tick, calls runReminderTick() and catches any unhandled rejection from it — logs the error to stdout as { event: 'scheduler_tick_error', error: message } without crashing the process
    • Logs { event: 'scheduler_started' } to stdout when registration succeeds
  • runReminderTick(): Promise<void> (also exported — exported so it can be exercised directly)

    • Computes currentMinuteUtc: the current UTC time with seconds and milliseconds zeroed (the start of the current minute)
    • Calls getDueReminders(currentMinuteUtc) from server/reminders/service.ts to retrieve all active reminders
    • For each DueReminder, performs these checks in order — skip the reminder if any check fails:
      1. Time check: convert remindAtTime (a "HH:MM" string in the user's userTimezone) to a UTC time for today; if the hour and minute do not match currentMinuteUtc's hour and minute, skip
      2. Recurrence check: determine today's day of the week in userTimezone; if that day is not in the habit's recurrence_days (retrieved by querying the habit row), skip. Because getDueReminders does not return recurrence_days, fetch the habit record using getHabitById from server/habits/service.ts — pass the habit's userId as the userId argument.
      3. Completion check: query check_ins for at least one row where habit_id matches, user_id matches, and checked_at falls within the current calendar day in userTimezone (expressed as UTC timestamps for the day's start and end). If a check-in exists, skip (already completed today).
    • If all three checks pass, calls sendEmail from server/email/client.ts using the reminderEmailTemplate from server/email/templates.ts
    • If sendEmail throws ExternalServiceError: logs { event: 'reminder_send_failed', userId: DueReminder.userId, habitId: DueReminder.habitId, error: message } to stdout and continues to the next reminder without rethrowing
    • On successful send: logs { event: 'reminder_sent', userId: DueReminder.userId, habitId: DueReminder.habitId } to stdout

Update server/index.ts

Import startScheduler from server/scheduler/index.ts and call it once after the server begins listening. Do not call it before the server is listening — the scheduler tick may attempt database queries, and the database connection should be confirmed alive before scheduling begins.

Do not build yet: user settings routes or any frontend files.


Check before continuing (do this yourself, do not paste it):

  • Restart the server (run npm run dev in the Shell). The Shell output should include a log line containing scheduler_started.
  • Set a reminder for the current time (or one minute from now) on a habit that is scheduled for today and has no check-in yet. Wait for the next minute to tick over. The Resend dashboard's sent log should show the email was sent.
  • Log a check-in for that habit, then wait for the same reminder time to fire again (or set a new reminder for the next minute). The email should not be sent a second time, and the Shell log should not contain reminder_sent for that habit.
  • If something is wrong: paste the Shell log output back to the agent and ask it to fix the scheduler logic before continuing.

Prompt 8

Run this after Prompt 7 is complete.

You'll end up with user settings endpoints — users can update their timezone or email address, and permanently delete their account. Deleting an account removes all associated habits, check-ins, reminders, and partnerships automatically via the database's cascade rules set up in Prompt 1.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–7 established the schema, server, auth, habits, reminders, social features, email, and the scheduler. This prompt adds user settings: updating timezone and email, and deleting the account.

server/users/validation.ts

Exports Zod schemas. These files must not import any Node.js-only modules so they can be bundled by Vite for the frontend in Prompt 9.

Export:

  • updateUserSchema — object with timezone (string, optional) and email (Zod email string, optional); refined so that at least one of the two fields must be present (use .refine to enforce this, with the message 'At least one field must be provided')
  • deleteAccountSchema — object with confirmEmail (string, required)

server/users/service.ts

Exports async service functions. The PublicUser shape used here is { id: string, email: string, timezone: string } — the same shape returned by auth routes.

  • updateUser(userId: string, data: { timezone?: string, email?: string }): Promise<PublicUser>

    • If email is provided, queries the users table to check whether any other user already owns that email (case-insensitive); throws ConflictError with the message 'An account with this email already exists' if so
    • Updates the matching fields on the user row
    • Returns the updated user as PublicUser
  • deleteUser(userId: string, confirmEmail: string): Promise<void>

    • Looks up the user by userId; throws NotFoundError if not found
    • Compares confirmEmail to the stored email case-insensitively; throws ValidationError with the message 'Email confirmation does not match your account email' if they do not match
    • Deletes the user row; the database cascade constraints from Prompt 1 remove all associated habits, check-ins, reminders, and partnerships automatically

server/users/routes.ts

Exports an Express Router. All routes require requireAuth. Mount this router in server/router.ts at /users.

  • PATCH /users/me

    • Validates the request body with updateUserSchema; on failure throws ValidationError
    • Calls updateUser(req.user.id, data)
    • Responds with { user: PublicUser }
  • DELETE /users/me

    • Validates the request body with deleteAccountSchema; on failure throws ValidationError
    • Calls deleteUser(req.user.id, confirmEmail)
    • Destroys the session after successful deletion (calls req.logout and req.session.destroy)
    • Responds with { success: true }

Validation errors from Zod must be caught at the route layer and thrown as ValidationError.

Do not build yet: any frontend files.


Check before continuing (do this yourself, do not paste it):

  • PATCH /users/me with { "timezone": "America/New_York" } should return the updated user with the new timezone.
  • PATCH /users/me with an email address that already belongs to another account should return 409.
  • DELETE /users/me with the correct confirmEmail should return { success: true }; a subsequent GET /auth/me with the same session should return 401.
  • DELETE /users/me with the wrong confirmEmail should return 400 with a message containing 'Email confirmation does not match'.
  • If something is wrong: paste the error back to the agent and ask it to fix before continuing.

Prompt 9

Run this after Prompt 8 is complete.

You'll end up with the complete browser interface — every screen the user interacts with, wired to the API you've built. After this prompt, the app is fully functional end-to-end: users can register, create habits, log check-ins, receive email reminders, invite accountability partners, and view leaderboards, all from the browser.


Paste everything below into your AI coding tool:

We are building a Strata on Replit. Prompts 1–8 built the complete backend: database, server, auth, habits, reminders, social features, email, scheduler, and user settings. This prompt builds the complete React frontend. It is compiled by Vite and served statically by Express from the public/ directory.

Vite configuration

Create a vite.config.ts at the project root that:

  • Sets the root to client/
  • Sets the build output directory to ../public (relative to the client root), so the compiled bundle lands in the public/ directory that Express already serves statically
  • Configures a development proxy so that requests from the frontend to /auth, /habits, /social, /users, and /health are forwarded to the Express server — this prevents CORS issues during local development

Create client/tsconfig.json configured for React with JSX support, targeting modern browsers.

client/src/lib/api.ts

A typed fetch wrapper. Every component and hook uses this — no component calls fetch directly.

Export:

  • apiFetch<T>(path: string, options?: RequestInit): Promise<T>
    • Ensures the path begins with /
    • Sets credentials: 'include' on every request so session cookies are sent
    • On a response that is not OK: reads the response body, extracts the error field from { error: string }, and throws an Error using that message
    • On a network failure: throws an Error with a user-friendly message such as 'Unable to connect to the server'
    • On success: parses and returns the response body as T

client/src/lib/auth.tsx

Exports:

  • AuthProvider — a React context provider that fetches GET /auth/me on mount to hydrate the current user; renders its children immediately (does not block render while loading)
  • useAuth(): { user: PublicUser | null, isLoading: boolean, setUser: (u: PublicUser | null) => void }
    • PublicUser: { id: string, email: string, timezone: string } — same shape as the backend's PublicUser
    • isLoading is true until the initial /auth/me fetch resolves

client/src/components/ProtectedRoute.tsx

  • Wraps routes that require authentication
  • If isLoading is true, renders a loading indicator
  • If user is null (and not loading), redirects to /login
  • Otherwise renders the child route

Component and page files

Create the following files. Each file's responsibilities are described below. Do not create any files beyond this list.

client/src/
  pages/
    LoginPage.tsx
    RegisterPage.tsx
    DashboardPage.tsx
    HabitDetailPage.tsx
    HabitFormPage.tsx
    SocialPage.tsx
    SettingsPage.tsx
  components/
    ProtectedRoute.tsx
    HabitCard.tsx
    CheckInButton.tsx
    StreakBadge.tsx
    PartnerCard.tsx
    LeaderboardTable.tsx
    ReminderForm.tsx
  lib/
    api.ts
    auth.tsx

Page responsibilities:

  • LoginPage.tsx — email/password login form (validates with loginSchema imported from server/auth/validation.ts) and a Google OAuth button that navigates to GET /auth/google. On successful login, updates the auth context and redirects to /.

  • RegisterPage.tsx — registration form (validates with registerSchema from server/auth/validation.ts). On success, updates the auth context and redirects to /.

  • DashboardPage.tsx — fetches GET /habits and displays each habit using HabitCard. Shows a button to navigate to /habits/new. Shows today's completion status for each habit.

  • HabitDetailPage.tsx — fetches GET /habits/:habitId and GET /habits/:habitId/checkins. Displays the habit's details, check-in history with notes, a CheckInButton, a StreakBadge, and a ReminderForm for managing reminders.

  • HabitFormPage.tsx — used for both creating (/habits/new) and editing (/habits/:habitId/edit) a habit. Validates with createHabitSchema (from server/habits/validation.ts) for create and updateHabitSchema for edit. On save, navigates to the dashboard.

  • SocialPage.tsx — displays: a form to invite a partner by email (calls POST /social/partners/invite); a list of existing partnerships using PartnerCard; a public habit discovery search input that calls GET /social/discover; a LeaderboardTable populated from GET /social/leaderboard.

  • SettingsPage.tsx — displays a form to update timezone and email (validates with updateUserSchema from server/users/validation.ts), and a delete-account section with a confirmation email input (validates with deleteAccountSchema). After account deletion, redirects to /login.

Component responsibilities:

  • HabitCard.tsx — displays a habit's name, category, and StreakBadge. Includes a CheckInButton for logging today's completion. Accepts habit: HabitWithStreak as a prop and an onCheckIn callback.

  • CheckInButton.tsx — a button that opens an optional note input and calls POST /habits/:habitId/checkins on submit. Accepts habitId: string and onSuccess: () => void as props.

  • StreakBadge.tsx — displays the current streak count with a visual indicator. Accepts streak: number as a prop.

  • PartnerCard.tsx — displays a partner's email and a link to view their public habits at /social/partners/:partnerUserId/habits. Accepts partnership: PartnershipWithUser as a prop.

  • LeaderboardTable.tsx — renders leaderboard entries in ranked order. Accepts entries: LeaderboardEntry[] as a prop.

  • ReminderForm.tsx — lists existing reminders for a habit, provides an input to add a new one (time picker or text input for HH:MM), and delete buttons for each existing reminder. Accepts habitId: string as a prop and manages its own reminder state by calling the reminders API.

Form validation

Create a top-level shared/ directory with a shared/validation.ts file. Move all Zod schemas (registerSchema, loginSchema, createHabitSchema, updateHabitSchema, updateUserSchema, deleteAccountSchema) into this file. Forms in LoginPage, RegisterPage, HabitFormPage, and SettingsPage must import and use the Zod schemas directly from this shared/ directory. Both the server/ and client/ directories must import the Zod schemas from shared/validation.ts to prevent Vite and TypeScript module resolution panics. Do not duplicate any schema.

client/src/main.tsx

The React entry point. Sets up AuthProvider and React Router with the following routes:

Path Component Protected
/login LoginPage No
/register RegisterPage No
/ DashboardPage Yes
/habits/new HabitFormPage Yes
/habits/:habitId HabitDetailPage Yes
/habits/:habitId/edit HabitFormPage Yes
/social SocialPage Yes
/settings SettingsPage Yes
* Redirect to / —

Build

After creating all files, run vite build to compile the frontend bundle into public/. Confirm the build succeeds before considering this prompt done.

Do not build: any new backend files. All server-side code is complete from earlier prompts.


Check before continuing (do this yourself, do not paste it):

  • Run npm run build in the Shell. It should complete without TypeScript or Vite errors and place files in public/.
  • Open your Repl's public URL. Without being logged in, you should be redirected to /login.
  • Register a new account — you should land on the Dashboard with zero habits.
  • Create a habit with at least one recurrence day. The Dashboard should display it with a streak of 0.
  • Click the check-in button for the habit. The streak should increment to 1.
  • Navigate to Settings, change your timezone, and return to the Dashboard — the streak display should remain consistent.
  • If something is wrong: paste the browser console error or the build error back to the agent and ask it to fix before considering the build complete.

Guide

Before You Build

The Before You Build guide details the prerequisite service accounts (Replit, Neon, Resend) and OAuth provider setups (Google) required prior to executing Prompt 1 of the Strata Replit Prompt Pack generated by Zalcro.

How to Use This Prompt Pack

This pack is a sequence of prompts you paste, one at a time, into Replit's AI agent to build your Strata from scratch. You don't need to understand the technical details — just follow the steps in order, confirm each one works before moving on, and let the agent do the building.


What You're Building

A web app where users create daily habits, track their streaks, and hold each other accountable. People can set email reminders, make habits public so others can see how many people share the same goal, invite friends as accountability partners to view each other's progress, and compete on leaderboards. Everything runs in a single Replit project — no separate services to manage.


What's in This Pack

9 prompts, in this order:

  1. Project scaffold and database schema — Sets up the full project structure and all database tables
  2. Express server, middleware, and security baseline — Starts the server with security headers, sessions, and CORS
  3. Authentication — Email/password registration and login, plus Google OAuth sign-in
  4. Habits and check-ins API — Create habits, log completions, and calculate streaks
  5. Reminders API — Configure what time each day to receive email reminders
  6. Social features — Accountability partners, public habit discovery, and leaderboards
  7. Background scheduler and email reminders — Sends reminder emails automatically every minute
  8. User settings — Update timezone, email address, and delete account
  9. React frontend — The complete browser interface connecting everything together

How Replit Works — What to Expect

Replit's AI agent reads your prompt and edits files directly in your project. It may suggest its own approach to a problem — accept it if it lines up with what the prompt asks for, and redirect it by pasting the relevant part of the prompt again if it goes off course. After each prompt, use the Shell tab to run any migration or build commands the verification block asks about. The agent does not run those for you automatically.

Run prompts in order. Each one assumes the previous is complete and working. If something breaks, use Replit's built-in version history to roll back — connect a Git repository before starting so you have a reliable fallback at every step.


Before You Run Prompt 1 — Complete These Steps First

1. Create Your Replit Project

  • Create a new Repl using the Node.js template.
  • Enable Always On in the Repl's settings panel (requires a paid Replit plan). Without this, your reminder emails will stop firing whenever the Repl goes idle.

2. Add a PostgreSQL Database

  • In your Repl's left sidebar, open the Database tool and provision a PostgreSQL database. Replit creates and connects it automatically.
  • Once provisioned, the DATABASE_URL secret is added to your environment automatically — confirm it appears in your Secrets panel before continuing.

3. Set Up Resend (Email Sending)

  • Sign up at resend.com.
  • Go to Domains, add the domain you want to send from (a subdomain like mail.yourdomain.com works), and follow Resend's instructions to add the SPF and DKIM records to your domain's DNS. Skipping this means your emails will land in spam.
  • Once the domain is verified, go to API Keys and create a new key. Copy it immediately.
  • Note your verified sender address (for example, reminders@mail.yourdomain.com). This is the "from" address for all emails the app sends.

4. Set Up Google OAuth

  • Go to console.cloud.google.com and create a new project.
  • Navigate to APIs & Services → OAuth consent screen. Fill in your app name and support email, then save.
  • Navigate to APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID. Choose Web application.
  • Under Authorized redirect URIs, add: https://your-repl-name.your-username.replit.dev/auth/google/callback — substituting your actual Repl URL.
  • Copy the Client ID and Client Secret.

5. Add Your Secrets

Open the Secrets panel (padlock icon in the sidebar) and add each of these. Never paste secrets into your source files.

Variable Where to find it
DATABASE_URL Auto-added by Replit when you provision the database — confirm it's there
SESSION_SECRET Make up any random string of 32 or more characters
RESEND_API_KEY Resend dashboard → API Keys
EMAIL_FROM Your verified Resend sender address, e.g. reminders@mail.yourdomain.com
GOOGLE_CLIENT_ID Google Cloud Console → Credentials → your OAuth 2.0 client
GOOGLE_CLIENT_SECRET Same location as above
APP_URL Your full Repl URL, e.g. https://your-repl-name.your-username.replit.dev