Core System Design & Tech Stack
This document provides a comprehensive technical breakdown of the system design, runtime execution environments, request lifecycles, and architectural patterns implemented in veridex-hitech-web-application.
1. Runtime Environment & Execution Boundaries
The platform operates across two distinct execution environments provided by Next.js 15: the Edge Runtime (lightweight, globally distributed) and the Node.js Runtime (full server environment with native filesystem and database driver support).
1.1 Edge Runtime Scope (src/middleware.ts)
The Edge runtime processes requests before any server route or layout renders. To maintain sub-5ms latency and avoid Edge compatibility failures:
- No Mongoose or Database Drivers: The Edge runtime cannot open raw TCP sockets to MongoDB. Middleware inspects
authjs.session-token,__Secure-authjs.session-token, ornext-auth.session-tokencookie presence purely via string evaluation. - Apex Host Header Evaluation: Resolves
x-forwarded-host,host, andx-forwarded-prototo redirectwww.hitechinsurance.aitohttps://hitechinsurance.aiusing HTTP 301 Permanent Redirects. - Path Stripping & Rewrite Logic: Maps legacy paths (e.g.
/locationto/locations,/claimsto/file-a-claim, and 20 legacy insurance product slugs) to their canonical destinations while preserving query parameters (searchParams). - QR Event Short Links: Intercepts short URLs matching
/e/:slugand issues a 307 Temporary Redirect to the localized landing page/en/e/:slug.
1.2 Node.js Server Runtime Scope
All page rendering, Server Actions, API route handlers, and database operations execute in the Node.js 22 runtime:
- Full access to the Mongoose ODM, MongoDB connection pooling, and aggregation pipelines.
- Native Buffer manipulation for HMAC-SHA256 signature calculation and verification.
- Local filesystem access to binary database files for
geoip-liteIP resolution. - Asynchronous task dispatch for email notifications and downstream CRM forwarding.
2. Request Lifecycle: Step-by-Step Traces
2.1 Public Form Submission via Server Action
The diagram below traces an interactive form submission (e.g., Quote Request or Scheduled Callback) from the browser through validation, bot filtering, persistence, and downstream sync:
3. Database Connection Architecture (src/lib/db/mongoose.ts)
In serverless and containerized Node.js environments, opening new database connections on every incoming request quickly exhausts MongoDB connection limits and introduces 200ms–500ms connection latency.
The platform implements a cached connection singleton pattern:
// Architectural Pattern: Cached Mongoose Connection Singleton
interface MongooseCache {
conn: typeof mongoose | null;
promise: Promise<typeof mongoose> | null;
}
declare global {
var mongoose: MongooseCache | undefined;
}
let cached: MongooseCache = global.mongoose || { conn: null, promise: null };
export async function connectDB(): Promise<typeof mongoose> {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts: mongoose.ConnectOptions = {
bufferCommands: false,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongooseInstance) => {
return mongooseInstance;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}
Connection Pool Configuration Parameters
maxPoolSize: 10: Limits concurrent open sockets per Node.js worker, preventing socket exhaustion during high-concurrency spikes.bufferCommands: false: Disables command buffering when the connection drops, throwing immediate actionable errors rather than stalling client requests indefinitely.serverSelectionTimeoutMS: 5000: Fast 5-second timeout on initial replica set election to prevent hanging worker threads.socketTimeoutMS: 45000: Cleans up stale idle sockets across NAT firewalls.
4. Server Actions vs. REST API Routes: Architectural Boundaries
The platform intentionally divides responsibilities between Next.js Server Actions and REST API Route Handlers:
| Operational Dimension | Server Actions (src/server/actions) | REST API Routes (src/app/api) |
|---|---|---|
| Primary Consumer | Internal first-party UI components | External partners, webhooks, mobile apps, telemetry beacons |
| Transport | Next.js RPC protocol over HTTP POST | Standard HTTP (GET, POST, PATCH, DELETE) |
| Authentication | Session cookie (auth()) or public form token | HMAC-SHA256 headers, API cookies, webhook challenge handshakes |
| Type Safety | End-to-end TypeScript inference with UI components | OpenAPI 3.0 contract and Zod request body schemas |
| Payload Size Limit | 8 MB (bodySizeLimit: "8mb" in next.config.ts) | Governed by body parsers (e.g. 2 MB for avatar uploads) |
| Use Cases | Quote forms, customer dashboard, blog CMS, bulk email | HMAC partner ingestion, Meta webhooks, /api/signatures/[id], heartbeat |
5. Security & Payload Boundaries
- Server Action Body Limit (8 MB): Configured in
next.config.tsunderexperimental.serverActions.bodySizeLimit: "8mb". Required because the Privacy Intake Form and Claim Submission Form allow policyholders to upload PDF documents and incident photos (up to 4 MB), which inflate by ~33% when base64-encoded. - User Avatar Payload Limit (2 MB): Enforced in
/api/user/profile/avatar. Rejects payloads larger than 2 MB and validates data URI MIME types (image/png,image/jpeg,image/webp). - Bulk Email Attachment Limit (3 MB Total): Enforced in the Admin Bulk Email Suite (
BulkEmailTab). Caps outgoing campaign attachments to 3 files and a combined binary payload of 3.0 MB. - Structured Error Handling: Server errors are intercepted and sanitized through
src/lib/server-errors.ts. Database stack traces and connection strings are masked from client responses.