# What Are the Core Modules in the TREK Server? Purpose and Architecture

> Discover the purpose of TREK server core modules. Learn how they initialize the server, enforce security, and provide essential services like authentication and WebSocket sync for all addons and features.

- Repository: [Maurice/TREK](https://github.com/mauriceboe/TREK)
- Tags: architecture
- Published: 2026-06-27

---

**The core modules serve as the foundational building blocks that initialize the TREK server, enforce security policies, and expose essential low-level services—such as authentication, database access, and real-time WebSocket synchronization—that every addon and feature depends on.**

The core modules in the `mauriceboe/TREK` repository constitute the essential infrastructure of the backend. They bootstrap the NestJS application, manage the SQLite database connection, and establish the secure communication channels required for collaborative travel planning features.

## Server Initialization and Configuration

The core modules begin execution by reading the **core environment variables** defined in the README's Core section. In [`server/src/config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/config.ts), the application parses critical variables including `PORT`, `NODE_ENV`, `ENCRYPTION_KEY`, `TZ`, and `LOG_LEVEL` to configure the HTTP server, WebSocket server, and global application settings.

This initialization sequence creates the NestJS application instance and establishes the foundational runtime environment before any addon modules load.

## Authentication and Session Management

Security policies are enforced through [`server/src/middleware/auth.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/auth.ts), which implements the core authentication stack. The module handles:

- **JWT-based login** for token verification
- **OIDC SSO** integration for enterprise identity providers
- **WebAuthn passkeys** for passwordless authentication
- **Multi-factor authentication (MFA)** workflows

The session management derives the `trek_session` cookie and its expiry from core settings (`SESSION_DURATION*`), ensuring consistent security across all client interactions.

## Database Connection and Persistence

Core modules provide the single source of truth for data access through [`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts). This module:

1. Opens the SQLite database at `data/travel.db`
2. Executes database migrations on startup
3. Exports the `db` object for consumption by all service layers

Any addon—including trip management, reservations, or packing lists—imports this core `db` instance to ensure unified data persistence.

## Real-Time WebSocket Infrastructure

Collaborative features rely on the WebSocket server initialized in [`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts). The core module starts the `ws` endpoint at `/ws`, enabling real-time synchronization for:

- Collaborative trip planning
- Live chat functionality
- Interactive polls and voting

Without this core WebSocket infrastructure, real-time state synchronization across clients would be impossible.

## Global Middleware and Security Layers

The [`server/src/middleware/globalMiddleware.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/globalMiddleware.ts) file registers essential middleware that processes every incoming request:

- **CORS** configuration for cross-origin requests
- **Rate limiting** to prevent abuse
- **Idempotency** handling for safe retry semantics
- **Request validation** for data integrity

These middleware functions run before any addon-specific logic, enforcing security and reliability at the application edge.

## Core API Routing

In [`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts), the core modules register the base `/api/*` routes that forward requests to various service layers. This central routing table acts as the dispatch layer, connecting incoming HTTP requests to the appropriate trip, place, weather, or reservation services.

## Practical Implementation Examples

### Accessing Core Database Services

Addons and higher-level services import the core database instance to maintain data consistency:

```typescript
import { db } from '@/db/database';   // core DB instance
import { Trip } from '@/db/schema';    // core schema

export async function getTripSummary(tripId: number) {
  const trip = await db.select().from(Trip).where({ id: tripId });
  // Business logic …
  return trip;
}

```

All services—such as [`tripService.ts`](https://github.com/mauriceboe/TREK/blob/main/tripService.ts) and [`reservationService.ts`](https://github.com/mauriceboe/TREK/blob/main/reservationService.ts)—depend on this core `db` object exported from [`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts).

### Initializing the WebSocket Server

Real-time features require the core WebSocket module:

```typescript
import { createWsServer } from '@/websocket';

const ws = createWsServer(app);   // `app` is the NestJS core instance
ws.on('connection', (socket) => {
  console.log('Client connected →', socket.id);
});

```

The WebSocket server created by this core module powers every real-time feature, from collaboration to live map updates.

### Docker Deployment with Core Variables

When deploying the TREK server, you must provide the core environment variables required by [`server/src/config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/config.ts):

```bash
ENCRYPTION_KEY=$(openssl rand -hex 32) \
docker run -d -p 3000:3000 \
  -e ENCRYPTION_KEY=$ENCRYPTION_KEY \
  -e PORT=3000 \
  -e NODE_ENV=production \
  -v ./data:/app/data \
  -v ./uploads:/app/uploads \
  mauriceboe/trek

```

The `ENCRYPTION_KEY`, `PORT`, and `NODE_ENV` variables belong to the **Core** group that the server reads at startup, as documented in the environment variables section of the README.

## Summary

The core modules in TREK provide the essential infrastructure that makes the travel planning platform functional:

- **Bootstrap the application** by reading configuration from [`server/src/config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/config.ts) and initializing the NestJS runtime in [`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)
- **Enforce security** through JWT, OIDC, WebAuthn, and MFA implementations in [`server/src/middleware/auth.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/auth.ts)
- **Maintain data integrity** via the single SQLite connection exported from [`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts)
- **Enable real-time collaboration** through the WebSocket server defined in [`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts)
- **Protect all endpoints** with global middleware for CORS, rate limiting, and validation in [`server/src/middleware/globalMiddleware.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/globalMiddleware.ts)

Without these foundational modules, the TREK server could not start, authenticate users, or maintain synchronized state across clients.

## Frequently Asked Questions

### What happens if core modules fail to initialize?

If core modules fail during startup—for example, if [`server/src/config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/config.ts) cannot read required environment variables like `ENCRYPTION_KEY` or `PORT`, or if [`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts) cannot open the SQLite file at `data/travel.db`—the TREK server will exit immediately with an error code. This fail-fast behavior prevents the server from running in an undefined state where security or data persistence might be compromised.

### How do addons interact with core modules?

Addons interact with core modules by importing the exported singletons and services. For instance, any addon requiring database access imports `db` from `@/db/database`, while real-time features import `createWsServer` from `@/websocket`. This dependency injection pattern ensures addons utilize the same authentication sessions, database connections, and WebSocket infrastructure managed by the core.

### Can core modules be customized or disabled?

Core modules cannot be disabled without breaking the TREK server, as they provide essential functionality like HTTP server initialization and database connectivity. However, you can customize their behavior through environment variables defined in the Core section of the README. For example, you can adjust `SESSION_DURATION`, `LOG_LEVEL`, or `CORS_ORIGIN` values to modify how [`server/src/config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/config.ts) and [`server/src/middleware/globalMiddleware.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/globalMiddleware.ts) behave without modifying source code.

### What is the difference between core modules and addons?

Core modules—located in `server/src/` paths like [`config.ts`](https://github.com/mauriceboe/TREK/blob/main/config.ts), [`database.ts`](https://github.com/mauriceboe/TREK/blob/main/database.ts), and [`auth.ts`](https://github.com/mauriceboe/TREK/blob/main/auth.ts)—provide foundational infrastructure that every feature requires. Addons (such as Packing, Vacay, or Atlas) are higher-level feature modules that plug into these core services but do not handle server initialization, database connections, or authentication themselves. The core modules bootstrap first, then expose APIs that addons consume to implement specific travel planning functionality.