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.
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.
@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.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.
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 family | Purpose | Access |
|---|---|---|
| /api/activities · /api/templates | List/detail; templates also support slug lookup | Public reads |
| /api/social-story-templates · /api/social-story-visuals | Story and visual catalog; stories support slug lookup | Public reads |
| /api/routine-categories · /api/story-categories | Category lists | Public reads |
| /api/resource-requests · /api/feedback | Create community submissions | Public POST, 5/min each |
| /api/template-feedback | Create/update helpfulness choice | Public POST, 30/min |
| /api/admin/… | Catalog management, categories, story pages, uploads, submissions | Bearer token + admin role |
| /api/admin/templates/import-csv /api/admin/social-story-templates/import-csv | CSV import; append /preview for preview endpoints | Admin POST |
| /api/admin/dashboard · /template-feedback · /inactive-resources | Reporting (all paths under /api/admin) | Admin reads |
| /health · /sitemap.xml · /uploads/:filename | Basic health status, sitemap, local images | Public; health does not query the database |
| /api-docs | Swagger UI, OpenAPI JSON and YAML | Registered 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.
Your dependency reference.
All 14 runtime and 4 development dependencies from package.json, with their roles verified against this archive.
| Runtime package | What it does in your service | Source anchor |
|---|---|---|
| @aws-sdk/client-s3 | Connects 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/express | clerkMiddleware 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 |
| compression | Compresses 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 |
| cors | Allows 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 |
| dotenv | Loads .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 |
| express | Builds 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-limit | Limits 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 |
| helmet | Adds browser security headers, including content-type, framing, referrer, and content-policy protections through helmet(). It complements authentication and input validation. | app.js |
| multer | Reads 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 |
| pg | Uses 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/ |
| sharp | Validates 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-express | Displays 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 |
| yaml | Confirmed: parses docs/openapi.yaml into the JavaScript specification passed to Swagger UI. The module checks the OpenAPI version before registration. | swagger.js |
| zod | Confirmed: 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
| Package | Purpose and evidence |
|---|---|
| @electric-sql/pglite | Confirmed in tests: creates an embedded PostgreSQL engine for database-backed tests without a separate server. Production uses pg.Pool. |
| eslint | Runs JavaScript checks through lint and lint:fix scripts. |
| @eslint/js | Provides standard JavaScript lint configurations. Exact applied rules cannot be confirmed: no ESLint config is included in the archive. |
| globals | Provides 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.
Startup, safeguards, and boundaries.
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.
Where to look next.
| Area | Files inspected |
|---|---|
| Entry and configuration | package.json · server.js · app.js · config/environment.js · config/db.js |
| Authentication and safeguards | middleware/requireAdminAuth.js · validation.js · errorHandler.js · logger.js |
| Images | routes/admin/adminUploadRoutes.js · controllers/imageController.js · services/imageService.js · r2ImageService.js · localImageService.js |
| Routes and content | routes/ · controllers/ · services/admin/ · migrations/ · tests/fixtures/baseline-schema.sql |
| Public submissions | routes/communitySubmissionRoutes.js · routes/templateFeedbackRoutes.js |
| Documentation and tests | swagger.js · tests/service.test.js · tests/* test imports and database fixtures |