# Main TREK Source Files: Complete Backend and Frontend Architecture Guide

> Explore the main TREK source files, including the Node.js backend and React frontend architecture along with database and state management details. Understand the complete TREK project structure.

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

---

**The main TREK source files comprise a Node.js/NestJS backend under `server/` and a React-TypeScript frontend under `client/`, with critical entry points at [`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts) and [`client/src/main.tsx`](https://github.com/mauriceboe/TREK/blob/main/client/src/main.tsx), database logic in [`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts), and state management via Redux slices in `client/src/store/`.**

TREK is a full‑stack travel‑planning application composed of a Node.js/NestJS backend and a React‑TypeScript frontend. Understanding the main TREK source files is essential for developers contributing to the codebase or customizing the travel‑planning workflow. The repository follows a clear separation between server‑side persistence logic and client‑side state management, with specific files handling database access, authentication, business rules, and real‑time communication.

## Backend Source Files (Node.js/NestJS)

The backend source files reside in the `server/src/` directory and follow a modular NestJS‑style architecture. These files handle HTTP request processing, SQLite database operations, JWT authentication, and WebSocket broadcasting.

### Application Entry and Bootstrap

**[`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)** serves as the primary application entry point. It starts the HTTP server, creates required data folders, and builds the Nest application instance.

**[`server/src/bootstrap.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/bootstrap.ts)** performs early‑stage setup including directory creation, environment loading, and calls the `buildApp` function to construct the configured application.

### Database Layer

**[`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts)** defines the SQLite schema and exports the `db` object used throughout the backend. It provides helper functions such as `isOwner` for ownership verification and manages database connections and migrations.

### Business Logic and Services

**[`server/src/services/tripService.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/tripService.ts)** contains the core business logic for trip management, including CRUD operations for trips, days, places, and reservations. The `createTrip` function handles reminder day validation, SQL insertion, and day generation:

```ts
// server/src/services/tripService.ts (excerpt)
export function createTrip(userId: number, data: CreateTripData, maxDays?: number) {
  const rd = data.reminder_days !== undefined
    ? (Number(data.reminder_days) >= 0 && Number(data.reminder_days) <= 30 ? Number(data.reminder_days) : 3)
    : 3;

  const result = db.prepare(`
    INSERT INTO trips (user_id, title, description, start_date, end_date, currency, reminder_days)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `).run(
    userId,
    data.title,
    data.description || null,
    data.start_date || null,
    data.end_date || null,
    data.currency || 'EUR',
    rd
  );

  const tripId = result.lastInsertRowid;
  generateDays(tripId, data.start_date || null, data.end_date || null, maxDays, data.day_count);
  const trip = db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId });
  return { trip, tripId: Number(tripId), reminderDays: rd };
}

```

### Middleware and Security

**[`server/src/middleware/auth.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/auth.ts)** validates JWT tokens on incoming requests, handles session checks, and enforces multi‑factor authentication (MFA) requirements. This file sits between the route handlers and the core services to ensure authorized access.

### Real‑Time Communication

**[`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts)** implements the WebSocket server for publishing real‑time updates to connected clients. It handles connection management and broadcasts trip updates to subscribed users.

## Frontend Source Files (React/TypeScript)

The frontend source files live under `client/src/` and implement a Redux‑Toolkit architecture with reusable utilities, API wrappers, custom hooks, and UI components.

### Entry Point and Configuration

**[`client/src/main.tsx`](https://github.com/mauriceboe/TREK/blob/main/client/src/main.tsx)** acts as the Vite boot script that mounts the React application to the DOM. The build configuration resides in **[`client/vite.config.ts`](https://github.com/mauriceboe/TREK/blob/main/client/vite.config.ts)**, which defines the development server settings and production build pipeline.

### API Client Layer

**[`client/src/api/client.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/api/client.ts)** provides a centralized wrapper around `fetch` for all backend endpoints. The `post` function handles JSON serialization, credential inclusion, and error handling:

```ts
// client/src/api/client.ts
export async function post<T = unknown>(path: string, body: unknown, opts?: RequestInit): Promise<T> {
  const resp = await fetch(`${BASE_URL}${path}`, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
    ...opts,
  });
  if (!resp.ok) throw await toApiError(resp);
  return resp.json() as Promise<T>;
}

// Usage
await post('/api/trips', { title: 'Paris', start_date: '2024-05-01', end_date: '2024-05-07' });

```

### State Management

**[`client/src/store/slices/todoSlice.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/store/slices/todoSlice.ts)** (alongside slices for trips, days, places, and packing) implements the Redux Toolkit state management. These slices define actions and reducers for immutable state updates across the application.

### Real‑Time Hooks

**[`client/src/hooks/useTripWebSocket.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/hooks/useTripWebSocket.ts)** is a React hook that establishes WebSocket connections to the server and dispatches incoming events to the Redux store:

```ts
// client/src/hooks/useTripWebSocket.ts
export function useTripWebSocket(tripId: string) {
  const dispatch = useAppDispatch();
  useEffect(() => {
    const ws = new WebSocket(`${WS_URL}/trip/${tripId}`);
    ws.onmessage = e => {
      const data = JSON.parse(e.data);
      if (data.type === 'tripUpdated') dispatch(updateTrip(data.payload));
    };
    return () => ws.close();
  }, [tripId, dispatch]);
}

```

### Utility Modules

**[`client/src/utils/formatters.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/utils/formatters.ts)** contains helper functions for date handling, unit conversion, currency formatting, and number manipulation used across UI components.

### Map Components

**[`client/src/components/Map/RouteCalculator.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/components/Map/RouteCalculator.ts)** handles map rendering, route calculations, point‑of‑interest (POI) display, and flight geometry visualization using the application's mapping library.

### Internationalization

**[`client/src/i18n/index.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/i18n/index.ts)** manages language resources and localization settings for the UI, supporting multiple languages through structured translation files.

## Summary

The main TREK source files form a cohesive full‑stack architecture:

- **[`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)** – Main entry point that initializes the HTTP server
- **[`server/src/bootstrap.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/bootstrap.ts)** – Early‑stage environment setup and application construction
- **[`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts)** – SQLite schema definitions and database access layer
- **[`server/src/services/tripService.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/tripService.ts)** – Core business logic for trip creation and management
- **[`server/src/middleware/auth.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/middleware/auth.ts)** – JWT validation and MFA enforcement
- **[`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts)** – Real‑time event broadcasting infrastructure
- **[`client/src/api/client.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/api/client.ts)** – Unified HTTP client for backend communication
- **[`client/src/hooks/useTripWebSocket.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/hooks/useTripWebSocket.ts)** – React hook for live data subscriptions
- **[`client/src/store/slices/todoSlice.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/store/slices/todoSlice.ts)** – Redux state management for application data
- **[`client/src/utils/formatters.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/utils/formatters.ts)** – Formatting helpers for dates and units
- **[`client/src/components/Map/RouteCalculator.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/components/Map/RouteCalculator.ts)** – Map‑based route calculation and visualization

## Frequently Asked Questions

### What is the entry point for the TREK backend server?

The **[`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)** file serves as the application entry point. According to the mauriceboe/TREK source code, this file starts the HTTP server, creates required data directories, and builds the Nest application instance before listening on the configured port.

### How does the frontend communicate with the backend in TREK?

The frontend uses **[`client/src/api/client.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/api/client.ts)**, a centralized wrapper around the `fetch` API. This module exports functions like `post`, `get`, `put`, and `delete` that handle credential inclusion, JSON serialization, and error formatting, ensuring consistent communication with the NestJS backend endpoints.

### Where is the database schema defined in TREK?

The SQLite database schema and connection logic reside in **[`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts)**. This file exports the `db` object used throughout the backend and includes helper functions such as `isOwner` for permission checks, along with SQL table definitions for trips, users, days, places, and reservations.

### Which file handles real‑time updates in the TREK frontend?

Real‑time updates are managed by **[`client/src/hooks/useTripWebSocket.ts`](https://github.com/mauriceboe/TREK/blob/main/client/src/hooks/useTripWebSocket.ts)**. As implemented in mauriceboe/TREK, this React hook creates a WebSocket connection to [`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts), listens for `tripUpdated` events, and dispatches Redux actions to synchronize the client state with server changes.