My Visual Path / Engineering field guide

How your Node.js
backend works.

A source-based walkthrough of the schedule service: architecture, working sequences, data storage, security, and every package we discussed.

Node.js ≥ 22Express 5PostgreSQLClerk + Cloudflare R2

Prepared 16 October 2026 · Source: supplied package.zip · No credentials included

01 / SYSTEM OVERVIEW

One API, three responsibilities.

The service delivers the public catalog, accepts community submissions, and protects content management behind Clerk admin authentication. PostgreSQL stores records; Cloudflare R2 stores image files.

Public browsing

Read activities, routine templates, social stories, visuals, and categories. No Clerk check is mounted on these public routes.

Community input

Submit resource requests, general feedback, and template helpfulness feedback through separately limited public endpoints.

Admin management

Manage catalog content, pages, categories, images, CSV imports, submissions, and reporting through /api/admin.

Website / admin browserJSON + multipart requests ClerkIdentity + admin metadata Node.js / Express service Logger → Helmet → CORS → rate limitBody parser → compression → route selection Public routesCatalog + submissions Admin routesBearer + Clerk + role Controllers → services → queriesValidation · catalog logic · image processing API requestsAdmin sign-in / token (frontend context)Verify identityFetch user role PostgreSQL · pg.PoolCatalog, URLs, feedback, imports Cloudflare R2 · image filesS3-compatible API + public image domainsharp → S3 client Records via APIBrowser fetches public image URLs directly from R2

Arrows show calls/dependencies; responses return to the caller. The frontend sign-in interaction is contextual: frontend source is not included in this archive. Local image storage is an alternate backend implemented by the service.

Why an AWS package with Cloudflare? @aws-sdk/client-s3 targets your Cloudflare R2 endpoint. It uses the S3 protocol; it does not mean your images are stored in AWS. This is R2 storage, not the separate Cloudflare Images API.
02 / WORKING SEQUENCES

Follow a request through the system.

Choose a scenario to see its sequence diagram. Each diagram reads from top to bottom. The steps below the diagram provide a text alternative.

    03 / DATA & ENDPOINTS

    What lives where.

    Routine content

    routine_categories classify activities and templates. template_activities links templates to their ordered activities.

    templates → template_activities → activities

    Social stories

    story_categories classify stories and visuals. Story template pages contain text, ordering, and an optional visual reference.

    social_story_templates → social_story_template_pages → social_story_visuals

    Submissions & imports

    community_submissions holds requests and feedback. template_feedback holds helpfulness choices. Import tables track identities/hashes; alias tables preserve previous slugs.

    Image URL fields connect database records to image files in R2. Uploading an image returns its URL and metadata; saving that URL on a catalog record is a separate operation.

    Route familyPurposeAccess
    /api/activities · /api/templatesList/detail; templates also support slug lookupPublic reads
    /api/social-story-templates · /api/social-story-visualsStory and visual catalog; stories support slug lookupPublic reads
    /api/routine-categories · /api/story-categoriesCategory listsPublic reads
    /api/resource-requests · /api/feedbackCreate community submissionsPublic POST, 5/min each
    /api/template-feedbackCreate/update helpfulness choicePublic POST, 30/min
    /api/admin/…Catalog management, categories, story pages, uploads, submissionsBearer token + admin role
    /api/admin/templates/import-csv
    /api/admin/social-story-templates/import-csv
    CSV import; append /preview for preview endpointsAdmin POST
    /api/admin/dashboard · /template-feedback · /inactive-resourcesReporting (all paths under /api/admin)Admin reads
    /health · /sitemap.xml · /uploads/:filenameBasic health status, sitemap, local imagesPublic; health does not query the database
    /api-docsSwagger UI, OpenAPI JSON and YAMLRegistered only when NODE_ENV=development

    This is a route-family map rather than an exhaustive endpoint specification. Route mounting and methods were checked against app.js and routes/. The public read-only gate runs after the public submission routes.

    04 / EVERYTHING WE DISCUSSED

    Your dependency reference.

    All 14 runtime and 4 development dependencies from package.json, with their roles verified against this archive.

    Runtime packageWhat it does in your serviceSource anchor
    @aws-sdk/client-s3Connects to Cloudflare R2. PutObjectCommand uploads conditionally; HeadObjectCommand compares stored SHA-256 metadata after a filename conflict. Matching images are reused; different images receive a hash suffix.services/r2ImageService.js
    @clerk/expressclerkMiddleware establishes authentication; getAuth reads the user ID; clerkClient.users.getUser retrieves the user. Custom middleware requires publicMetadata.role to equal admin.app.js; middleware/requireAdminAuth.js
    compressionCompresses eligible API responses according to browser support. Registered after the local /uploads route and before the main API routes. Does not resize images or process direct R2 downloads.app.js
    corsAllows configured origins, methods, Content-Type and Authorization. Exposes pagination and request-ID headers; preflight maxAge is 600 seconds. Unlisted supplied origins receive 403; requests without Origin pass this check. CORS is not authentication.app.js; config/environment.js
    dotenvLoads .env into process.env at startup with quiet mode. Environment settings configure PostgreSQL, Clerk, R2, origins, port, and local paths. It does not encrypt secrets.server.js
    expressBuilds the HTTP application and routers, runs middleware, parses JSON up to 64 KB, and sends responses. The app separates public routes from protected admin routes.app.js; routes/
    express-rate-limitLimits general traffic to 300/min, admin traffic to 60/min, public requests and feedback to 5/min each, and helpfulness feedback to 30/min. Default IP-based counters; exceeded limits return 429.app.js; communitySubmissionRoutes.js; templateFeedbackRoutes.js
    helmetAdds browser security headers, including content-type, framing, referrer, and content-policy protections through helmet(). It complements authentication and input validation.app.js
    multerReads multipart image uploads into memory as req.file.buffer. Accepts one image field, up to 5 MB, with type/name fields. MIME filtering is followed by sharp's actual image decoding.routes/admin/adminUploadRoutes.js
    pgUses PostgreSQL Pool connections for queries and transactions. Parameter placeholders carry values separately from SQL. Default pool size 10, configurable up to 50.config/db.js; services/
    sharpValidates JPEG/PNG/WebP, rejects multi-page input, limits decoding to 20 megapixels, corrects orientation, and fits within 1600×1600 without enlargement. R2 preserves format: JPEG/WebP quality 92, PNG compression 9. Local fallback produces WebP at quality 85.services/r2ImageService.js; localImageService.js
    swagger-ui-expressDisplays interactive API documentation at /api-docs in explicit development mode. Also provides /api-docs/openapi.json and /api-docs/openapi.yaml. Documentation comes from the supplied specification.swagger.js; app.js
    yamlConfirmed: parses docs/openapi.yaml into the JavaScript specification passed to Swagger UI. The module checks the OpenAPI version before registration.swagger.js
    zodConfirmed: validates catalog/category/page bodies, IDs, pagination, filters, URLs, and other fields. Strict schemas reject unexpected keys; safeParse failures become 400 errors with field details. Some submission routes use manual validation.middleware/validation.js; controllers/

    Development dependencies

    PackagePurpose and evidence
    @electric-sql/pgliteConfirmed in tests: creates an embedded PostgreSQL engine for database-backed tests without a separate server. Production uses pg.Pool.
    eslintRuns JavaScript checks through lint and lint:fix scripts.
    @eslint/jsProvides standard JavaScript lint configurations. Exact applied rules cannot be confirmed: no ESLint config is included in the archive.
    globalsProvides environment-specific global-name definitions for lint configuration. Actual configuration is not included.

    Earlier uncertainties about Multer, YAML, Zod, dotenv, and PGlite are resolved here by inspecting their actual usage. Package ranges are declarations, not proof of installed versions; the archive contains no lockfile.

    05 / RUNTIME BEHAVIOR

    Startup, safeguards, and boundaries.

    1 · Load settingsdotenv → environment validation → require Clerk keys
    →
    2 · ConnectCreate PostgreSQL pool from DATABASE_URL
    →
    3 · AssemblecreateApp mounts middleware and routes
    →
    4 · ListenDefault port 3001; graceful shutdown closes server and pool
    Authentication is separate from authorization

    Admin requests pass the global limiter and then an admin limiter. The middleware requires a Bearer header and removes request cookies before Clerk runs, preventing cookie fallback. Clerk uses configured authorizedParties. The next middleware obtains the user ID, fetches the Clerk user, and checks the admin role.

    Missing authentication → 401. Non-admin user → 403. Clerk user lookup failure → 503. The error handler replaces server-error messages with a generic message. No token or credential is embedded in this guide.

    Rate limits and upload capacity

    General: 300/min. Admin: 60/min shared across admin routes. Public resource requests: 5/min. Public general feedback: a separate 5/min. Template feedback: 30/min. Requests also count toward the general limit. Invalid submissions count because limiting occurs before validation.

    No shared limiter store is configured, so counters are local to each running process. TRUST_PROXY affects client-IP identification. Image uploads additionally allow at most two active uploads per router instance; excess attempts return 429.

    Image storage and caching

    Any nonempty R2 setting selects the R2 image service; that service then requires all five R2 settings. With no R2 settings, local storage is used. Partial R2 configuration is an error, not a silent local fallback.

    R2 writes use IfNoneMatch: * to avoid overwriting objects, SHA-256 metadata to identify matching content, and a one-year immutable cache header. Public catalog responses require revalidation; admin and submission responses use no-store. The configured public R2 domain must be distinct from the S3 API endpoint.

    CSV import workflow

    Admin routine and social-story routes provide preview and import endpoints. Import services parse and validate CSV, track import keys/content hashes, and use database transactions. Supporting code can resolve images from the configured frontend public-assets directory and upload them when enabled. That directory belongs to the wider project and is not included here.

    Logging, errors, and timeouts

    The logger assigns X-Request-Id and logs method, status, and elapsed time without headers or request bodies. The shared error handler maps validation and database failures to HTTP responses and hides internal error messages.

    Server request timeout: 15 seconds; headers timeout: 10 seconds. Pool connection timeout: 5 seconds; statement timeout: 7 seconds; query timeout: 8 seconds. Shutdown allows a 15-second deadline.

    What this guide verifies—and what it does not

    This guide documents source code in package.zip, not a live deployment. The frontend, deployment topology, active environment values, database contents, and installed dependency versions were not supplied. Diagrams are logical architecture rather than a hosting/network map.

    Tests and migrations are present. Tests were inspected but not executed for this documentation task. The archive does not include an ESLint configuration or lockfile. Formatting scripts reference Prettier, but it is not declared in this package.json; it may belong to the wider workspace. Startup does not automatically run migrations.

    Swagger routes are registered before the normal security middleware in development. swagger.js is imported at module load, so YAML parsing still occurs even when documentation routes are not registered.

    06 / SOURCE MAP

    Where to look next.

    AreaFiles inspected
    Entry and configurationpackage.json · server.js · app.js · config/environment.js · config/db.js
    Authentication and safeguardsmiddleware/requireAdminAuth.js · validation.js · errorHandler.js · logger.js
    Imagesroutes/admin/adminUploadRoutes.js · controllers/imageController.js · services/imageService.js · r2ImageService.js · localImageService.js
    Routes and contentroutes/ · controllers/ · services/admin/ · migrations/ · tests/fixtures/baseline-schema.sql
    Public submissionsroutes/communitySubmissionRoutes.js · routes/templateFeedbackRoutes.js
    Documentation and testsswagger.js · tests/service.test.js · tests/* test imports and database fixtures