Pular para o conteúdo

Shared Worker Concepts

All five Workers share a common foundation: D1 for data, KV for sessions, and the same CORS and auth patterns.

Workers

WorkerDirectoryRoutesPurpose
Authauth-worker//api/auth/*, /api/users/*Email/password auth, sessions
Billingbilling-worker//api/billing/*Stripe subscriptions
Listingslistings-worker//api/listings*Property CRUD, image uploads
Corretorescorretores-worker//api/corretores*Real estate agent registration
Chatchat-worker//api/chat/*, /api/ws, /api/search*, /api/admin/*AI chat, search, admin

Technology Stack

Each worker is built with:

  • TypeScript — source in src/
  • Wrangler — Cloudflare Workers CLI for dev and deploy
  • D1 — SQLite database for relational data
  • KV — Key-value store for sessions

Project Structure

Each worker directory follows the same layout:

{worker}/
├── src/
│ ├── index.ts # Worker entry point
│ ├── handlers.ts # Route handlers
│ └── types.ts # TypeScript types
├── package.json
├── tsconfig.json
└── wrangler.toml # Worker config, bindings, routes

Bindings

All workers declare the same bindings in wrangler.toml:

[[d1_databases]]
binding = "DB"
database_name = "redecasas-chat"
database_id = "..."
[[kv_namespaces]]
binding = "KV"
id = "..."

CORS

All workers import the shared CORS helper:

import { corsHeaders } from 'shared/src/cors';

This provides:

  • Dynamic origin validation
  • Access-Control-Allow-Credentials: true
  • Automatic preflight (OPTIONS) responses

Auth Validation

Protected endpoints follow this pattern:

  1. Read Cookie: session={token}
  2. const session = await env.KV.get(session:${token})
  3. Parse JSON, check expiresAt
  4. Query D1: SELECT * FROM users WHERE id = ?
  5. Attach user to context for the handler

Type Sharing

Common types live in shared/src/:

FileContents
cors.tsCORS helper functions
types.tsShared interfaces (User, Session, etc.)
auth/Auth-specific utilities