Lesson 1 of 9 · 24m
Vapor Routing and the Request Lifecycle
Read Vapor routes as a pipeline of grouping, decoding, authorization, side effects, and response encoding rather than as controller annotations.
The first Vapor outage I debugged looked like a routing bug and was actually a grouping bug: one sensitive route inherited the wrong middleware chain. Routing is not URL decoration. It is where transport input becomes typed input and where security policy begins.
Routes are typed entry points
func routes(_ app: Application) throws {
let api = app.grouped("api", "v1")
api.get("projects", ":projectID") { req async throws -> ProjectResponse in
guard let id = req.parameters.get("projectID", as: UUID.self) else {
throw Abort(.badRequest, reason: "projectID must be a UUID")
}
return try await ProjectResponse.load(id, on: req)
}
}:projectID is attacker-controlled text until converted. Convert early, fail narrowly, and never pass raw path fragments into queries or file paths.
Grouping is policy, not cosmetics
let publicRoutes = api.grouped(RateLimitMiddleware())
let session = api.grouped(SessionAuthMiddleware())
let admin = session.grouped(AdminOnlyMiddleware()).grouped("admin")Each layer adds a contract: public traffic is throttled, authenticated traffic has identity, admin traffic has a capability. Flattening those groups for tidiness is how a sensitive route ends up forums.
Know the lifecycle
socket -> HTTP parsing -> middleware -> route match
-> parameter/body decoding -> handler
-> response encoding -> error middleware -> clientWhen behavior differs between curl and a browser, inspect middleware before rewriting the handler. CORS, cookies, body collection, authentication, and error shaping all happen outside your closure.
Keep handlers thin
Use the path for object identity, query parameters for optional filters, headers for credentials and transport metadata, and bodies for representations. Cap pagination server-side; a client asking for limit=1000000 is making a request, not receiving a right. The handler should decode, authorize, invoke application logic, and encode — not contain every business rule inline.
Field notes
- A malformed UUID should normally be a 400 at the boundary, not a 500 from Fluent.
- Wildcard routes hide policy mistakes; prefer explicit routes for security-sensitive APIs.
GETmust not mutate meaningful state.- Log route templates, not raw paths full of object IDs, in metrics.
Was this lesson helpful?