# How the TREK Server Directory Structure Is Organized: A Complete Guide to the NestJS Backend

> Understand the TREK server directory structure. Explore the modular NestJS backend, from entry points and modules to services and testing, in this comprehensive guide.

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

---

**The TREK server directory structure follows a modular NestJS architecture where the `server/` folder contains a TypeScript backend organized into logical layers: entry points, bootstrap configuration, feature modules, middleware, services, database layer, and comprehensive test suites.**

The TREK backend is a modern TypeScript/NestJS application located under the repository's top-level `server/` directory, having fully replaced the legacy Express-based API. Understanding the TREK server directory structure is essential for developers contributing to the codebase, debugging issues, or extending functionality with new domain features. The architecture organizes code into distinct layers that map cleanly to product concepts, making navigation predictable and the system maintainable.

## Top-Level Server Organization

The `server/` folder serves as the root for all backend code. At this level, you will find configuration files ([`package.json`](https://github.com/mauriceboe/TREK/blob/main/package.json), [`vitest.config.ts`](https://github.com/mauriceboe/TREK/blob/main/vitest.config.ts), `.env.example`) alongside three primary directories:

- **`src/`** – Runtime source code including the NestJS application, modules, services, and utilities
- **`tests/`** – Unit, integration, and end-to-end test suites
- **`scripts/`** – Development and build automation scripts

Within `src/`, the code follows a layered architecture pattern where concerns are separated by responsibility rather than technical role.

## Entry Point and Bootstrap Process

### Application Entry ([`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts))

The server lifecycle begins in [`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts), which serves as the HTTP server entry point. This file performs several critical initialization tasks before handing control to NestJS:

```typescript
import 'reflect-metadata';
import 'dotenv/config';
import path from 'node:path';
import fs from 'node:fs';
import http from 'node:http';
import type { INestApplication } from '@nestjs/common';
import { buildApp } from './bootstrap';

```

The entry point creates required upload directories (`uploads/photos`, `uploads/avatars`), instantiates the raw HTTP server via `http.createServer()`, and invokes `buildApp()` from the bootstrap module. It also initializes scheduled background jobs (backups, demo resets, token cleanup) and sets up the WebSocket layer through `setupWebSocket`.

### Bootstrap Configuration ([`server/src/bootstrap.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/bootstrap.ts))

The [`bootstrap.ts`](https://github.com/mauriceboe/TREK/blob/main/bootstrap.ts) file contains the `buildApp()` function that constructs the Nest application. It registers **global pipes**, **CORS** configuration, **compression**, and applies the **global middleware** chain. Additionally, it registers platform routes for static uploads and SPA fallback handling through functions like `applyPlatformStatic`, `applyPlatformUploads`, and `applyPlatformSpa`.

## Core Module Architecture

### Root Module ([`server/src/app.module.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/app.module.ts))

The `AppModule` acts as the root **Nest module** that aggregates all domain-specific feature modules:

```typescript
@Module({
  imports: [
    DatabaseModule, WeatherModule, AirportsModule, ConfigModule,
    SystemNoticesModule, MapsModule, CategoriesModule, TagsModule,
    // ... additional feature modules
  ],
  controllers: [HealthController],
  providers: [
    HealthService,
    { provide: APP_FILTER, useClass: TrekExceptionFilter },
    { provide: APP_FILTER, useClass: SpaFallbackFilter },
    { provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor },
  ],
})
export class AppModule {}

```

This central registry declares all feature modules (weather, maps, trips, auth, budget, etc.) and configures global providers including exception filters and interceptors. Adding new functionality requires creating a domain module and registering it in this `imports` array.

## Feature Module Pattern

Each domain concept in the TREK server directory structure resides in its own feature folder under `server/src/<feature>/`. Taking the **trips** module as the canonical example:

- **[`server/src/nest/trips/trips.controller.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/nest/trips/trips.controller.ts)** – Defines REST endpoints such as `GET /api/trips` and `POST /api/trips/:id/assign`
- **[`server/src/services/tripService.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/services/tripService.ts)** – Contains core business logic including `createTrip()`, `updateDay()`, and `assignPlace()`
- **DTOs** – Typed request/response objects (e.g., `CreateTripDto`) for API contracts

Other features including `places/`, `budget/`, `packing/`, `collab/`, and `auth/` follow identical structural patterns, ensuring consistency across the codebase.

## MCP Integration Layer

The **Model-Context-Protocol (MCP)** integration resides in `server/src/mcp/`, enabling AI-driven extensions:

- **[`server/src/mcp/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/mcp/index.ts)** – Implements the MCP server and session management
- **`server/src/mcp/tools/`** – Individual tool implementations (e.g., `search_place`, `create_place`) that map directly to internal services
- **[`sessionManager.ts`](https://github.com/mauriceboe/TREK/blob/main/sessionManager.ts)** – Enforces per-user limits, token validation, and rate-limiting for AI sessions

Tools are registered via `registerTools()` in [`server/src/mcp/tools.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/mcp/tools.ts), exposing TREK's functionality to compatible AI clients.

## Middleware Stack

Express-style middlewares in `server/src/middleware/` run inside the Nest application and handle cross-cutting concerns:

| Middleware | Purpose |
|------------|---------|
| **[`auth.ts`](https://github.com/mauriceboe/TREK/blob/main/auth.ts)** | Verifies JWT/static tokens and attaches `req.user` |
| **[`validate.ts`](https://github.com/mauriceboe/TREK/blob/main/validate.ts)** | Runs Zod/JSON-schema validation on payloads |
| **[`idempotency.ts`](https://github.com/mauriceboe/TREK/blob/main/idempotency.ts)** | Guarantees safe retries via `X-Idempotency-Key` headers |
| **[`mfaPolicy.ts`](https://github.com/mauriceboe/TREK/blob/main/mfaPolicy.ts)** | Enforces MFA requirements on privileged endpoints |
| **[`globalMiddleware.ts`](https://github.com/mauriceboe/TREK/blob/main/globalMiddleware.ts)** | Central logging, request-ID generation, and timeout handling |

These middlewares are applied globally in [`bootstrap.ts`](https://github.com/mauriceboe/TREK/blob/main/bootstrap.ts) via `app.use(globalMiddleware)`.

## Database Layer

The database infrastructure in `server/src/db/` uses a Prisma-style approach:

- **[`schema.ts`](https://github.com/mauriceboe/TREK/blob/main/schema.ts)** – Defines the data model (Trip, Day, Place, Assignment, etc.)
- **[`migrations.ts`](https://github.com/mauriceboe/TREK/blob/main/migrations.ts)** – Runs at startup to maintain SQLite/Postgres schema compatibility
- **[`database.ts`](https://github.com/mauriceboe/TREK/blob/main/database.ts)** – Creates the Prisma client and exposes `closeDb()` for graceful shutdown
- **[`seeds.ts`](https://github.com/mauriceboe/TREK/blob/main/seeds.ts)** – Provides seed data for development and testing

## WebSocket and Real-Time Features

Real-time communication is configured in [`server/src/websocket.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/websocket.ts), which sets up the socket server for push notifications and collaborative features. This module is initialized from the main entry point after the HTTP server begins accepting connections.

## Testing Structure

The TREK server directory structure includes comprehensive testing under `server/tests/`:

- **`tests/unit/`** – Target individual services and middleware in isolation
- **`tests/integration/`** – Spin up the full Nest application and issue HTTP requests
- **`tests/e2e/`** – Validate complete request-response cycles including WebSocket events

Tests run via **Vitest** configured in [`server/vitest.config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/vitest.config.ts) and are executed with `pnpm test` or `npm test`.

## Development and Build Scripts

The `server/scripts/` directory contains automation helpers:

- **`dev.mjs`** – Launches the server in watch mode for development
- **`build.mjs`** – Compiles TypeScript for production deployment
- **[`migrate-encryption.ts`](https://github.com/mauriceboe/TREK/blob/main/migrate-encryption.ts)** – One-off data migration for encrypted fields
- **[`reset-admin.js`](https://github.com/mauriceboe/TREK/blob/main/reset-admin.js)** – Utility to re-initialize the default admin account

## Practical Code Examples

### Starting the Development Server

```bash

# Clone and install dependencies

git clone https://github.com/mauriceboe/TREK.git
cd TREK
pnpm install

# Run the dev script which creates upload dirs and starts Nest

pnpm dev   # executes server/scripts/dev.mjs

```

This ultimately runs [`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts), creating required directories before booting the Nest application.

### Adding a New Feature Module

```bash

# 1. Create scaffold

mkdir -p server/src/notifications
touch server/src/notifications/notifications.module.ts
touch server/src/notifications/notifications.controller.ts
touch server/src/notifications/notifications.service.ts

# 2. Register in root module

# Edit server/src/app.module.ts and add NotificationsModule to imports array

```

### Using a Service Directly

```typescript
import { TripService } from '../services/tripService';

async function demoCreateTrip() {
  const service = new TripService();
  const trip = await service.createTrip({
    name: 'Paris 2025',
    startDate: '2025-05-10',
    endDate: '2025-05-20',
    currency: 'EUR',
  });
  console.log('Created trip ID:', trip.id);
}

```

### Calling an MCP Tool

AI clients interact with TREK through the MCP layer:

```json
{
  "method": "search_place",
  "params": { "query": "Eiffel Tower", "tripId": "12345" }
}

```

This routes to [`server/src/mcp/tools/search_place.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/mcp/tools/search_place.ts) via the tools registration system.

## Summary

- The **TREK server directory structure** organizes code under `server/src/` with clear separation between entry points, bootstrap logic, feature modules, and cross-cutting concerns
- **[`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)** initializes the HTTP server, directories, and background jobs before delegating to NestJS
- **[`server/src/app.module.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/app.module.ts)** serves as the central registry for all domain modules and global providers
- Feature modules follow a consistent pattern with controllers, services, and DTOs co-located by domain
- The **MCP layer** (`server/src/mcp/`) exposes AI-compatible tools while middleware (`server/src/middleware/`) handles authentication, validation, and idempotency
- **Database operations** are centralized in `server/src/db/` with Prisma-style schema definitions
- **Testing** spans unit, integration, and E2E layers under `server/tests/`, executed by Vitest

## Frequently Asked Questions

### Where is the main entry point in the TREK server directory structure?

The main entry point is **[`server/src/index.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/index.ts)**, which creates the HTTP server, initializes upload directories, and invokes `buildApp()` from the bootstrap module. This file also sets up scheduled background jobs and initializes the WebSocket server before starting to accept connections.

### How do I add a new feature module to the TREK server?

Create a new directory under `server/src/<feature>/` containing a Nest module file, controller, and service. Then register the module in **[`server/src/app.module.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/app.module.ts)** by adding it to the `imports` array. This pattern maintains the modular architecture where each domain (trips, places, budget, etc.) is self-contained and testable.

### What testing frameworks are used in the TREK server directory structure?

The project uses **Vitest** as the test runner, configured in [`server/vitest.config.ts`](https://github.com/mauriceboe/TREK/blob/main/server/vitest.config.ts). Tests are organized into three categories: unit tests for individual services/middleware, integration tests that spin up the full Nest application, and end-to-end tests that validate complete request cycles including WebSocket events. Run tests with `pnpm test` or `npm test`.

### How does the TREK server handle database connections?

Database connections are managed in **[`server/src/db/database.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/database.ts)**, which creates a Prisma client and exposes `closeDb()` for graceful shutdown. Schema definitions live in [`server/src/db/schema.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/schema.ts), while [`server/src/db/migrations.ts`](https://github.com/mauriceboe/TREK/blob/main/server/src/db/migrations.ts) runs automatically at startup to maintain schema compatibility across SQLite and PostgreSQL deployments.