SwiftX LogoSwiftX

Project Structure

Best practices for organizing a large SwiftX server.

Project Structure Guide

For small projects, a single main.swift or a few files is fine. But as your project grows, you should organize it for better maintainability and developer velocity.

Ultimate Big Server Structure

A professional SwiftX project should separate its concerns to make it easy to work on specific parts of the logic.

main.swift
Package.swift
.env

Step-by-Step Organization

Move Handlers to Separate Files

Instead of writing inline closures in main.swift, define your handler functions as public functions.

// Sources/MyProject/handlers/users.swift
import SwiftX

public func userProfileHandler(req: Req, ctx: Context) -> Res {
    let id = req.param("id") ?? "0"
    return .json(["id": id])
}

Group Routes Together

Use app.group to organize your API paths.

// Sources/MyProject/main.swift
import SwiftX

app.group("/api/v1") { api in
    api.get("/user/:id", handler: userProfileHandler)
    api.post("/user", handler: createUserHandler)
}

Use Services for Logic

Keep your handlers thin. Move complex logic, database queries, and third-party API calls into separate services.

// Sources/MyProject/services/Database.swift
public class DatabaseService {
    public static func findUser(by id: String) -> User? {
        // ... db logic here
    }
}

Modular Architecture

For extremely large projects, you can even split your app into multiple Swift Packages, each with its own internal complexity, and bring them together in a single SwiftX server.

Pro Tip

Use separate Packages for core libraries, shared models, and independent feature modules.

On this page