What Does the Main Entry Point File in TREK Server Do?

The server/src/index.ts file serves as the primary startup script that initializes the TREK backend by preparing the environment, bootstrapping the NestJS application, launching background schedulers, and managing graceful shutdowns.

The main entry point in the TREK repository orchestrates the complete lifecycle of the backend server. Located at server/src/index.ts, this TypeScript file coordinates filesystem preparation, application bootstrapping, real-time WebSocket initialization, and signal-based shutdown procedures to ensure the application starts cleanly and exits safely.

Environment and Filesystem Preparation

Before the HTTP server begins accepting connections, the entry point prepares the runtime environment. During the initial phase (lines 1‑8), it loads environment variables via import 'dotenv/config' and initializes the NestJS reflection API.

The script then creates necessary directories for file operations. Between lines 10‑16, it defines paths for uploads, photos, files, covers, avatars, data/backups, and data/tmp. A forEach loop (lines 18‑20) ensures these directories exist by calling fs methods, preventing runtime errors when the application attempts to store uploads or backups.

NestJS Application Bootstrapping

The core application construction happens in the bootstrap() function (lines 94‑104). This async function imports buildApp from ./bootstrap.ts (line 7), which configures the NestJS modules, middleware, and global pipes.

The entry point wraps the NestJS HTTP adapter in a native Node.js http.Server instance. This hybrid approach allows the application to leverage NestJS's dependency injection while maintaining direct access to the underlying server for WebSocket integration and graceful shutdown handling.

Runtime Banner and Background Jobs

Once the server begins listening, the onListen function (lines 29‑88) executes. It renders a colorful startup banner to the console displaying critical runtime information: version number, port, host, APP_URL, environment name, timezone, allowed CORS origins, log level, process ID, and user IDs.

Simultaneously, the entry point initiates background maintenance tasks. It calls scheduler.start*() methods (lines 75‑83) to begin:

  • Email reminder dispatch
  • Version checking routines
  • Demo environment resets
  • Cache cleanup operations

Finally, it initializes the WebSocket layer by invoking setupWebSocket (lines 86‑88), enabling real-time collaboration features for the frontend.

Graceful Shutdown Sequence

The entry point registers signal handlers for SIGTERM and SIGINT (lines 132‑133) to ensure zero-downtime deployments and safe exits. When triggered, the shutdown() function (lines 111‑130) executes a coordinated teardown sequence:

  1. Logs the shutdown event using logInfo from the audit service
  2. Stops all background schedulers to prevent orphaned jobs
  3. Closes active MCP (Model Context Protocol) sessions
  4. Shuts down the NestJS application and underlying HTTP server
  5. Flushes the SQLite database buffers
  6. Exits the process, with a forced timeout fallback if cleanup stalls

This systematic approach prevents data loss and ensures active requests complete before the process terminates.

Practical Startup Examples

Starting the Server Locally

To launch the TREK backend in development mode, run the following from the repository root:

npm run dev

This command executes the compiled server/src/index.ts entry point, which invokes the bootstrap() function and begins listening on the port defined by process.env.PORT (defaulting to 3001).

Verifying Health Status

Once running, verify the server is accepting connections:

curl http://localhost:3001/api/health

Because the entry point creates the HTTP server that forwards all routes to the NestJS application, this endpoint returns a JSON payload confirming the server status.

Customizing the Startup Banner

To display additional environment variables in the startup banner, modify the banner array inside the onListen function:

const banner = [
  // ...existing lines
  `  Custom Config: ${process.env.MY_CUSTOM_VAR || 'not set'}`,
];

After restarting the server, the new line appears in the console output alongside the standard runtime information.

Summary

  • server/src/index.ts is the main entry point file in TREK server that orchestrates the entire backend lifecycle.
  • It creates required directories (uploads, photos, backups, etc.) before the application starts serving traffic.
  • It bootstraps the NestJS application via buildApp() and wraps it in a native Node.js HTTP server.
  • It prints a diagnostic banner and starts background schedulers for maintenance tasks, WebSocket services, and email reminders.
  • It implements graceful shutdown handling for SIGTERM and SIGINT signals to ensure clean database flushing and connection termination.

Frequently Asked Questions

What port does the TREK server use by default?

The TREK server defaults to port 3001 when the PORT environment variable is not specified. This value is read from process.env.PORT during the bootstrap phase in server/src/index.ts.

Which directories does the TREK server create on startup?

According to the source code in server/src/index.ts (lines 10‑20), the server automatically creates the following directories if they do not exist: uploads, photos, files, covers, avatars, data/backups, and data/tmp. These paths support file uploads, avatar storage, cover images, and database backup operations.

How does TREK handle graceful shutdowns?

The entry point registers listeners for SIGTERM and SIGINT signals (lines 132‑133) that trigger the shutdown() function. This function stops background schedulers, closes MCP sessions, shuts down the NestJS application and HTTP server, flushes the SQLite database, and exits the process cleanly to prevent data corruption.

What background tasks does the TREK scheduler run?

The scheduler initialized in server/src/index.ts (lines 75‑83) manages several background jobs including email reminder dispatch, version checking, demo environment resets, and cache cleanup. These tasks run asynchronously to keep the application state synchronized without blocking HTTP requests.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →