Strata: Social Habit Tracker
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 | 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
- Create a new Repl using the Node.js template.
- Enable Always On for your Repl (found in the Repl's settings panel). This is what keeps your reminder scheduler alive between requests.
- 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.
- 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
- After signing up, go to Domains and add the domain you want to send email from (even a subdomain like
mail.yourdomain.comworks). - 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.
- Once the domain is verified, create an API key from the API Keys section. Copy it immediately; you won't see it again.
- 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
- In Google Cloud Console, create a new project.
- 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).
- Go to APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID. Choose "Web application."
- Under "Authorized redirect URIs," add:
https://your-repl-url.replit.dev/auth/google/callback— replacing the domain with your actual Repl URL from above. - 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 valueRESEND_API_KEY— Resend dashboard → API Keys → your keyEMAIL_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 clientGOOGLE_CLIENT_SECRET— same location as aboveAPP_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 onexpire
Exported TypeScript types (inferred by Drizzle):
User,NewUser— select and insert shapes forusersHabit,NewHabit— select and insert shapes forhabitsCheckIn,NewCheckIn— select and insert shapes forcheck_insReminder,NewReminder— select and insert shapes forremindersAccountabilityPartner,NewAccountabilityPartner— select and insert shapes foraccountability_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.jsonscripts:"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 generateproduces a valid SQL migration file with all six tables, indexes, and constraints - Running
drizzle-kit migrateagainst the Replit database applies the migration without errors db/index.tsexports adbclient that can execute a simpleSELECT 1query 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-sessionAPP_URL— used as the only allowed CORS originDATABASE_URL— consumed by connect-pg-simple for session storage
Session configuration:
- Cookie:
httpOnly: true,sameSite: 'strict',secure: true - Store: connect-pg-simple using the
dbconnection - 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?.idif 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, takesmessage: stringandstatusCode: numberNotFoundError extends AppError— status 404; used when a resource doesn't exist or the caller isn't authorized to know it existsUnauthorizedError extends AppError— status 401; used when no valid session existsValidationError extends AppError— status 400; used when Zod rejects inputConflictError 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 /healthwith{ 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:
- Look up the user by email (case-insensitive)
- If no user found, fail with the message
'Invalid email or password' - Compare the submitted password against
password_hashusing bcrypt - If the hash doesn't match, fail with the same message (do not distinguish between "no user" and "wrong password")
- On success, pass the full
Userobject to the done callback
GoogleStrategy behavior:
- Receive the Google profile's email and
google_id(the profile'sidfield) - Look up an existing user by
google_idfirst - If found, pass that user to done
- If not found by
google_id, look up by email - If found by email, update that user's
google_idto link the accounts, pass the updated user - If neither match, create a new
Userwithpassword_hash: null, setgoogle_id, pass the new user - On any database error, pass the error to done
Session serialization:
serializeUser: storesuser.id(string) in the sessiondeserializeUser: looks up the fullUserbyid; if not found, passesnull(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 newUser; establish a session; return{ user: PublicUser } PublicUsershape:{ id: string, email: string, timezone: string }— never includespassword_hashorgoogle_id
- Accepts:
POST /auth/login- Accepts:
{ email: string, password: string } - Delegates to Passport LocalStrategy; on success return
{ user: PublicUser }; on failure returnUnauthorizedError
- Accepts:
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
- OAuth callback; on success redirect to
POST /auth/logout- Destroys the session; returns
{ success: true }
- Destroys the session; returns
GET /auth/me- Requires
requireAuth; returns{ user: PublicUser }for the current session's user
- Requires
server/middleware/requireAuth.ts
Exports a single Express middleware:
requireAuth(req, res, next): void- If
req.isAuthenticated()is true, callsnext() - 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/registerwith a valid body creates a user, returns aPublicUser, and sets a session cookiePOST /auth/loginwith correct credentials returns aPublicUserand sets a session cookiePOST /auth/loginwith wrong credentials returns a 401 with{ error: 'Invalid email or password' }GET /auth/mewith 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_normalizedvianormalizeHabitName - Inserts the habit and returns the full
Habitrow
updateHabit(habitId: string, userId: string, data: Partial<CreateHabitInput>): Promise<Habit>- Verifies ownership (throws
NotFoundErrorif the habit doesn't exist or doesn't belong touserId) - If
nameis indata, recomputesname_normalized - Updates only the provided fields; returns the updated
Habit
- Verifies ownership (throws
archiveHabit(habitId: string, userId: string): Promise<void>- Verifies ownership; sets
archived_atto now; does not delete the row
- Verifies ownership; sets
getHabitsForUser(userId: string): Promise<Habit[]>- Returns all non-archived habits for the user (where
archived_at IS NULL)
- Returns all non-archived habits for the user (where
getHabitById(habitId: string, userId: string): Promise<Habit>- Returns the habit if it exists and belongs to
userId; throwsNotFoundErrorotherwise - 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)
- Returns the habit if it exists and belongs to
createCheckIn(habitId: string, userId: string, data: { note: string | null }): Promise<CheckIn>- Verifies the habit exists and belongs to
userId(viagetHabitById) - Sets
checked_atto the current server timestamp - Inserts and returns the
CheckInrow
- Verifies the habit exists and belongs to
getCheckInsForHabit(habitId: string, userId: string): Promise<CheckIn[]>- Verifies ownership; returns all check-ins for the habit, ordered by
checked_at DESC
- Verifies ownership; returns all check-ins for the habit, ordered by
calculateStreak(habitId: string, recurrenceDays: number[], userTimezone: string): Promise<number>- Fetches check-in dates for the habit from the database, ordered descending
- Converts
checked_attimestamps to dates inuserTimezone - 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
recurrenceDaysare 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
getHabitByIdthencalculateStreak; returns the combined shape
getHabitsWithStreaks(userId: string, userTimezone: string): Promise<HabitWithStreak[]>- Calls
getHabitsForUserthencalculateStreakfor each result - Returns the array of
HabitWithStreak
- Calls
server/habits/routes.ts
Exports an Express Router mounted at /habits. All routes require requireAuth.
GET /habits→ callsgetHabitsWithStreaks(req.user.id, req.user.timezone); returns{ habits: HabitWithStreak[] }POST /habits→ validates withcreateHabitSchema; callscreateHabit; returns{ habit: Habit }with a 201 statusGET /habits/:habitId→ callsgetHabitWithStreak; returns{ habit: HabitWithStreak }PATCH /habits/:habitId→ validates withupdateHabitSchema; callsupdateHabit; returns{ habit: Habit }DELETE /habits/:habitId→ callsarchiveHabit; returns{ success: true }POST /habits/:habitId/checkins→ validates withcreateCheckInSchema; callscreateCheckIn; returns{ checkIn: CheckIn }with 201GET /habits/:habitId/checkins→ callsgetCheckInsForHabit; 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 /habitswith valid data creates a habit; the storedname_normalizedis lowercase and trimmed regardless of what the client sentGET /habitsreturns 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/:habitIdsetsarchived_atwithout deleting the row; the habit no longer appears inGET /habitsPOST /habits/:id/checkinsfrom 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 matchesHH:MMin 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
userIdby callinggetHabitByIdfrom the habits service - Inserts and returns the
Reminderrow
- Verifies the habit exists and belongs to
getRemindersForHabit(habitId: string, userId: string): Promise<Reminder[]>- Verifies ownership via
getHabitById - Returns all reminders for the habit
- Verifies ownership via
updateReminder(reminderId: string, userId: string, remindAtTime: string): Promise<Reminder>- Looks up the reminder; verifies
user_idmatches; throwsNotFoundErrorif not - Updates
remind_at_time; returns the updated row
- Looks up the reminder; verifies
deleteReminder(reminderId: string, userId: string): Promise<void>- Looks up the reminder; verifies
user_idmatches; throwsNotFoundErrorif not - Deletes the row
- Looks up the reminder; verifies
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_timeto UTC using the user's timezone and comparing tocurrentMinuteUtc
server/reminders/routes.ts
Exports an Express Router mounted at /habits/:habitId/reminders. All routes require requireAuth.
GET /habits/:habitId/reminders→ callsgetRemindersForHabit; returns{ reminders: Reminder[] }POST /habits/:habitId/reminders→ validates withcreateReminderSchema; callscreateReminder; returns{ reminder: Reminder }with 201PATCH /habits/:habitId/reminders/:reminderId→ validates withupdateReminderSchema; callsupdateReminder; returns{ reminder: Reminder }DELETE /habits/:habitId/reminders/:reminderId→ callsdeleteReminder; returns{ success: true }
Deliverables:
POST /habits/:habitId/reminderswith a valid time creates a reminder; attempts from non-owners return 404GET /habits/:habitId/remindersreturns all reminders for that habitDELETE /habits/:habitId/reminders/:reminderIdfrom a non-owner returns 404getDueReminderscalled 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_FROMfrom the environment as the sender address - On success, returns
undefined - On any failure (network error, API error, invalid recipient), throws
ExternalServiceErrorwith 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
NotFoundErrorif no account exists with that email - Checks whether a partnership record already exists between requester and addressee (in either direction); throws
ConflictErrorif so - Calls
sendEmailwith the invitation template; ifsendEmailthrowsExternalServiceError, re-throws it — no database record is created - If the email succeeds, inserts the
AccountabilityPartnerrow withstatus: 'pending' - Returns the new row
- Looks up the addressee user by email; throws
respondToInvite(partnershipId: string, addresseeId: string, response: 'accepted' | 'rejected'): Promise<AccountabilityPartner>- Looks up the partnership; throws
NotFoundErrorif not found or ifaddressee_id !== addresseeId - Throws
ConflictErrorif the current status is not'pending' - Updates
statusto the given response; returns the updated row
- Looks up the partnership; throws
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
NotFoundErrorif 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
calculateStreakfrom the habits service
- Verifies an accepted partnership exists between viewer and partner (in either direction); throws
getPublicHabitCount(nameNormalized: string, category: string | null): Promise<number>- Counts distinct users tracking a public habit with the given
name_normalized - If
categoryis provided, adds it as a filter condition (category-scoped matching per ADD Risk 3 mitigation) - Returns the count as a number
- Counts distinct users tracking a public habit with the given
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
categoryif provided) - Computes streak for each using the habit owner's timezone
- Sorts by streak descending; returns the top
limitentries (maximum 100)
server/social/routes.ts
Exports an Express Router mounted at /social. All routes require requireAuth.
POST /social/partners/invite— body:{ email: string }; callssendPartnerInvite(req.user.id, email); returns{ partnership: AccountabilityPartner }with 201PATCH /social/partners/:partnershipId— body:{ response: 'accepted' | 'rejected' }; callsrespondToInvite; returns{ partnership: AccountabilityPartner }GET /social/partners— callsgetPartnerships(req.user.id); returns{ partnerships: PartnershipWithUser[] }GET /social/partners/:partnerUserId/habits— callsgetPartnerHabits(req.user.id, partnerUserId); returns{ habits: HabitWithStreak[] }GET /social/discover— query param:name(required),category(optional); callsgetPublicHabitCount; returns{ count: number }GET /social/leaderboard— query param:category(optional),limit(optional, default 20, max 100); callsgetLeaderboard; returns{ leaderboard: LeaderboardEntry[] }
Deliverables:
POST /social/partners/invitewith a valid email sends an email via Resend and creates a partnership record; if called a second time for the same pair, returns 409POST /social/partners/invitewhen Resend throws returns an error response and no database record is created (verify by checking theaccountability_partnerstable)PATCH /social/partners/:idfrom the addressee with{ response: 'accepted' }updates the status; the same call from the requester returns 404GET /social/partners/:partnerUserId/habitswith no accepted partnership returns 404; with an accepted partnership returns only public habits with streak countsGET /social/leaderboardreturns 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.tsat 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
- Called once from
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, convertsremind_at_time(inuserTimezone) 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
userTimezoneis inrecurrence_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
sendEmailwith the reminder template fromserver/email/templates.ts - If
sendEmailthrowsExternalServiceError: 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_failedand 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.refineto 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
emailis provided, checks that no other user owns that email (throwsConflictErrorif taken) - Updates the user row; returns the updated
PublicUsershape ({ id, email, timezone })
- If
deleteUser(userId: string, confirmEmail: string): Promise<void>- Looks up the user; throws
NotFoundErrorif not found - Compares
confirmEmail(case-insensitive) to the user's stored email; throwsValidationErrorif 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
- Looks up the user; throws
server/users/routes.ts
Exports an Express Router mounted at /users. All routes require requireAuth.
PATCH /users/me— validates withupdateUserSchema; callsupdateUser(req.user.id, data); returns{ user: PublicUser }DELETE /users/me— validates withdeleteAccountSchema; callsdeleteUser(req.user.id, confirmEmail); destroys the session; returns{ success: true }
Deliverables:
PATCH /users/mewith{ timezone: 'America/New_York' }updates the user's timezone; subsequent streak calculations onGET /habitsreflect the new timezonePATCH /users/mewith an email already belonging to another account returns 409DELETE /users/mewith the correct email deletes the user and all their data; the session is destroyed; the same session cookie returns 401 on the next requestDELETE /users/mewith 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
Errorwith theerrorfield from{ error: string } - On a network failure, throws with a user-friendly message
- Returns the parsed JSON as
T
- Prepends
client/src/lib/auth.tsx
Exports:
AuthProvider— React context provider; fetchesGET /auth/meon mount to hydrate the current useruseAuth(): { user: PublicUser | null, isLoading: boolean, setUser: (u: PublicUser | null) => void }PublicUser:{ id: string, email: string, timezone: string }— same shape as the backend'sPublicUser
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"— runsvite buildto compile the React frontend"start"— runs the compiled server entry point (the output of the TypeScript compiler ortsx, whichever approach is idiomatic for Replit's Node.js environment)"dev"— runs both the Express server and Vite simultaneously usingconcurrently "tsx watch server/index.ts" "vite"for fast iteration."db:generate"— runsdrizzle-kit generateto produce migration SQL from the schema"db:migrate"— runsdrizzle-kit migrateto 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 onexpire.
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 forusers)Habit,NewHabit(select and insert types forhabits)CheckIn,NewCheckIn(select and insert types forcheck_ins)Reminder,NewReminder(select and insert types forreminders)AccountabilityPartner,NewAccountabilityPartner(select and insert types foraccountability_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 insidedb/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.tsordb/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 takesmessage: stringandstatusCode: number; exposes both as public propertiesNotFoundError extends AppError— fixed status 404; used when a resource doesn't exist or the requesting user isn't authorized to know it existsUnauthorizedError extends AppError— fixed status 401; used when no valid session existsValidationError extends AppError— fixed status 400; used when Zod rejects inputConflictError extends AppError— fixed status 409; used for constraint violations such as duplicate partnership invitesExternalServiceError 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?.idif a session user is present. The log must never include a stack trace, internal database error detail, or raw SDK error text. - If
erris an instance ofAppError, responds witherr.statusCodeand{ error: err.message } - For any other error type, responds with a generic server error status and
{ error: 'An unexpected error occurred' }
- Logs the error to stdout including the route path and
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:
- Helmet (default configuration)
- CORS — allowed origin is
APP_URLfrom the environment; credentials allowed; no wildcard - JSON body parser
- express-session with connect-pg-simple as the store:
- Session secret from
SESSION_SECRETenvironment variable - Cookie:
httpOnly: true,sameSite: 'strict',secure: true - Session max age: 30 days
- The connect-pg-simple store uses the same
DATABASE_URLthe rest of the app uses; it does not create a second Drizzle instance — it connects viapgdirectly as connect-pg-simple expects
- Session secret from
passport.initialize()andpassport.session()— Passport itself is configured in the next prompt; mount the middleware stubs here- Static file serving from the
public/directory at the project root (this serves the compiled React bundle added in Prompt 9) - Mount
routerfromserver/router.tsat/ - Mount
errorHandlerfromserver/middleware/errorHandler.tsas 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
/healthto 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 withemail(Zod email string) andpassword(string, minimum 8 characters)loginSchema— same shape asregisterSchema
server/middleware/requireAuth.ts
Exports a single Express middleware:
requireAuth(req, res, next): void- If
req.isAuthenticated()returns true, callsnext() - Otherwise throws
UnauthorizedError(imported fromserver/errors.ts)
- If
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'):
- Receives
emailandpasswordfrom the request body - Looks up the user in the
userstable by email (case-insensitive comparison) - If no user is found, calls done with the message
'Invalid email or password'— do not distinguish between "no account" and "wrong password" - Compares the submitted password against the stored
password_hashusing bcrypt - If the hash does not match, calls done with the same message
'Invalid email or password' - On success, passes the full
Userrow 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):
- Receives the Google profile's email and the profile's ID field as
google_id - Looks up an existing user by
google_idfirst; if found, passes that user to done - If not found by
google_id, looks up by email (case-insensitive) - If found by email, updates that user's
google_idfield to link the accounts, then passes the updated user to done - If neither lookup finds a match, creates a new
Userrow withpassword_hash: nullandgoogle_idset; passes the new user to done - On any database error, passes the error to done
Session serialization:
serializeUser: storesuser.id(the UUID string) in the sessiondeserializeUser: looks up the fullUserrow by that ID; if no user is found, passesnull(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 throwsValidationErrorwith the Zod error details - Checks for an existing user with the same email (case-insensitive); if found throws
ConflictErrorwith the message'An account with this email already exists' - Hashes the password with bcrypt at 12 rounds
- Inserts a new
Userrow - Establishes a session (calls
req.login) - Responds with status 201 and
{ user: PublicUser }
- Validates the request body with
POST /login- Validates the request body with
loginSchema; on failure throwsValidationError - Delegates to Passport LocalStrategy via
passport.authenticate('local', ...) - On success: responds with
{ user: PublicUser } - On failure: throws
UnauthorizedErrorwith the message returned by the strategy ('Invalid email or password')
- Validates the request body with
GET /google- Initiates Google OAuth redirect via Passport; requests
emailandprofilescopes
- Initiates Google OAuth redirect via Passport; requests
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
- Protected by
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/registerwith a valid email and password — you should receive{ user: { id, email, timezone } }with status 201. POST /auth/loginwith the same credentials should return the same shape.POST /auth/loginwith a wrong password should return a 401 with{ error: 'Invalid email or password' }.GET /auth/meimmediately 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 ascreateHabitSchema, all optional (partial), with the same individual field constraintscreateCheckInSchema— 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_normalizedfield 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_normalizedby callingnormalizeHabitName(data.name) - Inserts the habit row and returns the full
Habitrecord
updateHabit(habitId: string, userId: string, data: Partial<CreateHabitInput>): Promise<Habit>- Verifies that a habit with
habitIdexists and hasuser_id === userId; throwsNotFoundErrorif not - If
data.nameis present, recomputesname_normalized - Updates only the fields provided in
data - Returns the updated
Habitrecord
- Verifies that a habit with
archiveHabit(habitId: string, userId: string): Promise<void>- Verifies ownership (same check as
updateHabit); throwsNotFoundErrorif not - Sets
archived_atto the current timestamp; does not delete the row
- Verifies ownership (same check as
getHabitsForUser(userId: string): Promise<Habit[]>- Returns all habits where
user_id === userIdandarchived_at IS NULL
- Returns all habits where
getHabitById(habitId: string, userId: string): Promise<Habit>- Returns the habit if it exists and
user_id === userId; throwsNotFoundErrorotherwise - Returns archived habits as well — this function is the canonical ownership check used by check-in and reminder routes
- Returns the habit if it exists and
createCheckIn(habitId: string, userId: string, data: { note: string | null }): Promise<CheckIn>- Verifies the habit exists and belongs to
userIdby callinggetHabitById - Sets
checked_atto the current server UTC timestamp - Inserts and returns the
CheckInrow
- Verifies the habit exists and belongs to
getCheckInsForHabit(habitId: string, userId: string): Promise<CheckIn[]>- Verifies ownership via
getHabitById - Returns all check-ins for the habit ordered by
checked_at DESC
- Verifies ownership via
calculateStreak(habitId: string, recurrenceDays: number[], userTimezone: string): Promise<number>- Fetches all
checked_attimestamps for the habit fromcheck_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
- If the day is in
- 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
- Fetches all
getHabitWithStreak(habitId: string, userId: string, userTimezone: string): Promise<HabitWithStreak>HabitWithStreak: theHabittype intersected with{ streak: number }- Calls
getHabitByIdthencalculateStreak; returns the merged result
getHabitsWithStreaks(userId: string, userTimezone: string): Promise<HabitWithStreak[]>- Calls
getHabitsForUser, then callscalculateStreakfor each result - Returns the full array of
HabitWithStreak
- Calls
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— callsgetHabitsWithStreaks(req.user.id, req.user.timezone); responds with{ habits: HabitWithStreak[] }POST /habits— validates withcreateHabitSchema; callscreateHabit; responds with status 201 and{ habit: Habit }GET /habits/:habitId— callsgetHabitWithStreak(habitId, req.user.id, req.user.timezone); responds with{ habit: HabitWithStreak }PATCH /habits/:habitId— validates withupdateHabitSchema; callsupdateHabit; responds with{ habit: Habit }DELETE /habits/:habitId— callsarchiveHabit; responds with{ success: true }POST /habits/:habitId/checkins— validates withcreateCheckInSchema; callscreateCheckIn; responds with status 201 and{ checkIn: CheckIn }GET /habits/:habitId/checkins— callsgetCheckInsForHabit; 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 /habitswith{ name: "Exercise", is_public: true, recurrence_days: [1, 3], category: "health" }should create a habit and return it. Check thatname_normalizedin the response is"exercise"(lowercase).GET /habitsshould return the habit with astreakfield (0 at this point since there are no check-ins).POST /habits/:habitId/checkinsshould record a check-in and return it.DELETE /habits/:habitIdshould return{ success: true }; a subsequentGET /habitsshould no longer include that habit.POST /habits/:habitId/checkinsfor 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 timeHH:MM, e.g."14:30")updateReminderSchema— same shape ascreateReminderSchema
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
userIdby callinggetHabitByIdfromserver/habits/service.ts; throwsNotFoundErrorif not - Inserts a new
Reminderrow withhabit_id,user_id, andremind_at_time - Returns the inserted
Reminder
- Verifies the habit exists and belongs to
getRemindersForHabit(habitId: string, userId: string): Promise<Reminder[]>- Verifies ownership via
getHabitById - Returns all reminders for the habit
- Verifies ownership via
updateReminder(reminderId: string, userId: string, remindAtTime: string): Promise<Reminder>- Looks up the reminder by
reminderId; throwsNotFoundErrorif it doesn't exist or if itsuser_iddoes not matchuserId - Updates
remind_at_timeto the new value; returns the updatedReminder
- Looks up the reminder by
deleteReminder(reminderId: string, userId: string): Promise<void>- Looks up the reminder by
reminderId; throwsNotFoundErrorif it doesn't exist or if itsuser_iddoes not matchuserId - Deletes the row
- Looks up the reminder by
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
reminderstable joined tousers(foremailandtimezone) and joined tohabits(fornameandarchived_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— callsgetRemindersForHabit(habitId, req.user.id); responds with{ reminders: Reminder[] }POST /habits/:habitId/reminders— validates withcreateReminderSchema; callscreateReminder(habitId, req.user.id, remindAtTime); responds with status 201 and{ reminder: Reminder }PATCH /habits/:habitId/reminders/:reminderId— validates withupdateReminderSchema; callsupdateReminder(reminderId, req.user.id, remindAtTime); responds with{ reminder: Reminder }DELETE /habits/:habitId/reminders/:reminderId— callsdeleteReminder(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/reminderswith{ "remind_at_time": "08:00" }should create a reminder and return it.GET /habits/:habitId/remindersshould return the reminder you just created.DELETE /habits/:habitId/reminders/:reminderIdfrom 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_FROMfrom 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
ExternalServiceErrorwith 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
ExternalServiceErrorand 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
NotFoundErrorwith the message'No account found with that email address'if not found - Checks for any existing
accountability_partnersrow where(requester_id, addressee_id)matches in either direction; throwsConflictErrorwith the message'You already have a pending or active partnership with this user'if found - Calls
sendEmailwith the invitation template (usinginvitationEmailTemplate); ifsendEmailthrowsExternalServiceError, re-throws it immediately — no database record is written - If the email succeeds, inserts the
AccountabilityPartnerrow withstatus: 'pending' - Returns the newly created row
- Looks up the addressee by email (case-insensitive); throws
respondToInvite(partnershipId: string, addresseeId: string, response: 'accepted' | 'rejected'): Promise<AccountabilityPartner>- Looks up the partnership by
partnershipId; throwsNotFoundErrorif not found or ifaddressee_id !== addresseeId(the requester cannot respond to their own invite) - Throws
ConflictErrorwith the message'This invitation has already been responded to'if the current status is not'pending' - Updates
statustoresponse; returns the updated row
- Looks up the partnership by
getPartnerships(userId: string): Promise<PartnershipWithUser[]>- Returns all
accountability_partnersrows wherestatus = 'accepted'and the user is eitherrequester_idoraddressee_id - Joins to
usersto include the partner's email and timezone PartnershipWithUser:AccountabilityPartner & { partnerEmail: string, partnerTimezone: string }
- Returns all
getPartnerHabits(viewerUserId: string, partnerUserId: string): Promise<HabitWithStreak[]>- Verifies an accepted partnership exists between
viewerUserIdandpartnerUserId(in either direction); throwsNotFoundErrorif no accepted partnership exists - Returns only the partner's habits where
is_public = trueandarchived_at IS NULL - Calculates streak for each habit using the partner's timezone, by calling
calculateStreakfromserver/habits/service.ts - Returns
HabitWithStreak[]
- Verifies an accepted partnership exists between
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 givenname_normalized - If
categoryis not null, additionally filters bycategory - Returns the count as a number
- Counts the number of distinct users who have a public (
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 bycategoryif provided - For each habit, looks up the owner's timezone and calls
calculateStreak - Sorts results by
streakdescending - Returns the top
limitentries;limitmust 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); callssendPartnerInvite(req.user.id, email); responds with status 201 and{ partnership: AccountabilityPartner }PATCH /social/partners/:partnershipId— body:{ response: 'accepted' | 'rejected' }(validate with Zod inline); callsrespondToInvite(partnershipId, req.user.id, response); responds with{ partnership: AccountabilityPartner }GET /social/partners— callsgetPartnerships(req.user.id); responds with{ partnerships: PartnershipWithUser[] }GET /social/partners/:partnerUserId/habits— callsgetPartnerHabits(req.user.id, partnerUserId); responds with{ habits: HabitWithStreak[] }GET /social/discover— query params:name(required string),category(optional string); callsgetPublicHabitCount(nameNormalized, category ?? null)wherenameNormalizedis the result ofnormalizeHabitName(name)fromserver/habits/service.ts; responds with{ count: number }GET /social/leaderboard— query params:category(optional string),limit(optional integer, default 20, maximum 100); callsgetLeaderboard(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/invitewith 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/invitea second time for the same pair should return 409. PATCH /social/partners/:partnershipIdwith{ "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/leaderboardshould 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.tsafter 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
- Called once from
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)fromserver/reminders/service.tsto retrieve all active reminders - For each
DueReminder, performs these checks in order — skip the reminder if any check fails:- Time check: convert
remindAtTime(a"HH:MM"string in the user'suserTimezone) to a UTC time for today; if the hour and minute do not matchcurrentMinuteUtc's hour and minute, skip - Recurrence check: determine today's day of the week in
userTimezone; if that day is not in the habit'srecurrence_days(retrieved by querying the habit row), skip. BecausegetDueRemindersdoes not returnrecurrence_days, fetch the habit record usinggetHabitByIdfromserver/habits/service.ts— pass the habit'suserIdas theuserIdargument. - Completion check: query
check_insfor at least one row wherehabit_idmatches,user_idmatches, andchecked_atfalls within the current calendar day inuserTimezone(expressed as UTC timestamps for the day's start and end). If a check-in exists, skip (already completed today).
- Time check: convert
- If all three checks pass, calls
sendEmailfromserver/email/client.tsusing thereminderEmailTemplatefromserver/email/templates.ts - If
sendEmailthrowsExternalServiceError: 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
- Computes
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 devin the Shell). The Shell output should include a log line containingscheduler_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_sentfor 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 withtimezone(string, optional) andemail(Zod email string, optional); refined so that at least one of the two fields must be present (use.refineto enforce this, with the message'At least one field must be provided')deleteAccountSchema— object withconfirmEmail(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
emailis provided, queries theuserstable to check whether any other user already owns that email (case-insensitive); throwsConflictErrorwith 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
- If
deleteUser(userId: string, confirmEmail: string): Promise<void>- Looks up the user by
userId; throwsNotFoundErrorif not found - Compares
confirmEmailto the storedemailcase-insensitively; throwsValidationErrorwith 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
- Looks up the user by
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 throwsValidationError - Calls
updateUser(req.user.id, data) - Responds with
{ user: PublicUser }
- Validates the request body with
DELETE /users/me- Validates the request body with
deleteAccountSchema; on failure throwsValidationError - Calls
deleteUser(req.user.id, confirmEmail) - Destroys the session after successful deletion (calls
req.logoutandreq.session.destroy) - Responds with
{ success: true }
- Validates the request body with
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/mewith{ "timezone": "America/New_York" }should return the updated user with the new timezone.PATCH /users/mewith an email address that already belongs to another account should return 409.DELETE /users/mewith the correctconfirmEmailshould return{ success: true }; a subsequentGET /auth/mewith the same session should return 401.DELETE /users/mewith the wrongconfirmEmailshould 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 thepublic/directory that Express already serves statically - Configures a development proxy so that requests from the frontend to
/auth,/habits,/social,/users, and/healthare 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
errorfield from{ error: string }, and throws anErrorusing that message - On a network failure: throws an
Errorwith a user-friendly message such as'Unable to connect to the server' - On success: parses and returns the response body as
T
- Ensures the path begins with
client/src/lib/auth.tsx
Exports:
AuthProvider— a React context provider that fetchesGET /auth/meon 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'sPublicUserisLoadingistrueuntil the initial/auth/mefetch resolves
client/src/components/ProtectedRoute.tsx
- Wraps routes that require authentication
- If
isLoadingis true, renders a loading indicator - If
useris 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 withloginSchemaimported fromserver/auth/validation.ts) and a Google OAuth button that navigates toGET /auth/google. On successful login, updates the auth context and redirects to/.RegisterPage.tsx— registration form (validates withregisterSchemafromserver/auth/validation.ts). On success, updates the auth context and redirects to/.DashboardPage.tsx— fetchesGET /habitsand displays each habit usingHabitCard. Shows a button to navigate to/habits/new. Shows today's completion status for each habit.HabitDetailPage.tsx— fetchesGET /habits/:habitIdandGET /habits/:habitId/checkins. Displays the habit's details, check-in history with notes, aCheckInButton, aStreakBadge, and aReminderFormfor managing reminders.HabitFormPage.tsx— used for both creating (/habits/new) and editing (/habits/:habitId/edit) a habit. Validates withcreateHabitSchema(fromserver/habits/validation.ts) for create andupdateHabitSchemafor edit. On save, navigates to the dashboard.SocialPage.tsx— displays: a form to invite a partner by email (callsPOST /social/partners/invite); a list of existing partnerships usingPartnerCard; a public habit discovery search input that callsGET /social/discover; aLeaderboardTablepopulated fromGET /social/leaderboard.SettingsPage.tsx— displays a form to update timezone and email (validates withupdateUserSchemafromserver/users/validation.ts), and a delete-account section with a confirmation email input (validates withdeleteAccountSchema). After account deletion, redirects to/login.
Component responsibilities:
HabitCard.tsx— displays a habit's name, category, andStreakBadge. Includes aCheckInButtonfor logging today's completion. Acceptshabit: HabitWithStreakas a prop and anonCheckIncallback.CheckInButton.tsx— a button that opens an optional note input and callsPOST /habits/:habitId/checkinson submit. AcceptshabitId: stringandonSuccess: () => voidas props.StreakBadge.tsx— displays the current streak count with a visual indicator. Acceptsstreak: numberas a prop.PartnerCard.tsx— displays a partner's email and a link to view their public habits at/social/partners/:partnerUserId/habits. Acceptspartnership: PartnershipWithUseras a prop.LeaderboardTable.tsx— renders leaderboard entries in ranked order. Acceptsentries: 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 forHH:MM), and delete buttons for each existing reminder. AcceptshabitId: stringas 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 buildin the Shell. It should complete without TypeScript or Vite errors and place files inpublic/. - 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:
- Project scaffold and database schema — Sets up the full project structure and all database tables
- Express server, middleware, and security baseline — Starts the server with security headers, sessions, and CORS
- Authentication — Email/password registration and login, plus Google OAuth sign-in
- Habits and check-ins API — Create habits, log completions, and calculate streaks
- Reminders API — Configure what time each day to receive email reminders
- Social features — Accountability partners, public habit discovery, and leaderboards
- Background scheduler and email reminders — Sends reminder emails automatically every minute
- User settings — Update timezone, email address, and delete account
- 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_URLsecret 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.comworks), 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 |