Server Bootstrap and Middleware Pipeline
Server Bootstrap and Middleware Pipeline
Relevant source files
The following files were used as context for generating this wiki page:
The Primebrick v3 backend is built on Express.js and follows a structured initialization sequence designed for high availability and security. The bootstrap process ensures that the database connection pool is ready, identity provider (IDP) configurations are loaded, and a secure-first middleware pipeline is established before the server starts accepting traffic.
Initialization Sequence
The entry point of the application is src/index.ts. The bootstrap process follows a strict order to ensure dependencies are resolved before the HTTP server binds to a port.
Bootstrap Workflow
- Middleware Setup: Global middleware (CORS, JSON parsing, Cookie parsing) is registered src/index.ts:27-29.
- Public Health Check: The
/api/v1/healthendpoint is mounted early to allow infrastructure probes even if other components are still initializing src/index.ts:154-156. - OpenAPI Documentation: The OpenAPI router is mounted before any authentication guards to ensure the documentation remains accessible for client integration src/index.ts:161.
- Protected Router Creation: A
makeProtectedRouteris instantiated to enforce a "secure-first" policy for domain modules src/index.ts:164. - Module Mounting: Domain-specific routers (Customers, Organizations, Auth) are mounted to the Express application src/index.ts:175-179.
- Global Error Handling: The centralized
errorHandleris attached as the final middleware in the stack src/index.ts:181. - Data Pre-loading: Role mappings are fetched from the database and cached in memory src/index.ts:184.
- Server Start: The application begins listening on the configured
PORTsrc/index.ts:186-188.
Component Relationship Diagram
This diagram maps the high-level bootstrap concepts to the specific code entities responsible for them.
Title: Server Bootstrap Component Mapping
Code
Sources: src/index.ts:1-189, src/http/protected-router.ts:87-106
Middleware Stack
The middleware pipeline is divided into global utilities and domain-specific guards.
| Middleware | Source | Purpose |
|---|---|---|
cors | src/index.ts:27 | Enables Cross-Origin Resource Sharing (currently set to origin: true). |
express.json | src/index.ts:28 | Parses incoming requests with JSON payloads. |
cookieParser | src/index.ts:29 | Parses Cookie headers and populates req.cookies. |
rbacHandler | src/modules/auth/rbac.middleware.js:15 | Validates user permissions against the required Permission enum. |
errorHandler | src/http/error-handler.ts:4 | Catches all upstream errors and formats them into RFC 7807 responses. |
Secure-First Routing
The makeProtectedRouter factory src/http/protected-router.ts:87 wraps the standard Express Router. It enforces that every route registered using HTTP verbs (get, post, etc.) must include an rbacHandler. If a developer forgets to declare a permission, the router automatically injects a defaultDenyHandler src/http/protected-router.ts:38, which returns a 403 Forbidden with the internal code ROUTE_PERMISSION_NOT_DECLARED.
Sources: src/index.ts:27-29, src/http/protected-router.ts:1-107
Health Check and Diagnostics
The /api/v1/health endpoint provides a comprehensive status of the system's vital signs. It returns a 200 OK only if both the database and the Identity Provider (Casdoor) are reachable src/index.ts:149-150.
Health Check Logic
- Database: Executes a cheap
SELECT 1query using thegetPool()instance src/index.ts:54-64. - IDP (Casdoor): Attempts to fetch version information from the Casdoor API. It first tries to load configuration from the
auth_configtable in the database before falling back to environment variables src/index.ts:66-132.
Title: Health Check Data Flow
Code
Sources: src/index.ts:54-156
Centralized Error Handling
The system uses a centralized errorHandler src/http/error-handler.ts:4 to ensure all API responses follow the RFC 7807 (Problem Details for HTTP APIs) specification.
Error Classification
The handler distinguishes between several types of failures:
- ApiError: Custom errors (like
NotFoundErrororForbiddenError) that already contain RFC 7807 metadata src/http/api-errors.ts:32. - Database Unavailable: Detected via
isDatabaseUnavailableErrorsrc/http/api-errors.ts:197. It maps Postgres codes (e.g.,57P01,57P03) or network codes (e.g.,ECONNREFUSED) to a503 Service Unavailableresponse src/http/error-handler.ts:24-36. - Validation Errors: Produced by
validateBodyorvalidateQuerysrc/http/validation.ts:23-45. These use Zod schemas to validate input and return a400 Bad Requestwith a detailedissuesarray src/http/validation.ts:4-21. - Internal Server Error: Any unhandled exception is caught and returned as a
500 Internal Server Errorwith aHIGHseverity rating src/http/error-handler.ts:38-46.
RFC 7807 Response Structure
All errors returned to the client follow this schema:
type: A URI identifier for the error type.title: A short, human-readable summary.status: The HTTP status code.detail: A specific explanation of this occurrence.instance: The URI of the specific endpoint that failed.internal_code: A stable string for programmatic handling (e.g.,VALIDATION_ERROR).
Sources: src/http/error-handler.ts:4-47, src/http/api-errors.ts:1-224, src/http/validation.ts:1-45