Skip to content

The Request Lifecycle ​

Introduction ​

Knowing what happens between a request arriving and a response leaving makes the rest of the framework easier to reason about. In Plinth the journey is short and has one main actor, the HttpKernel. This page follows a request from the Node server to the response, and shows where middleware, routing, controllers, and the exception handler fit.

Overview ​

  1. src/server.ts boots the application: it creates the Application, loads configuration, and runs the service providers.
  2. The entry point builds a Router with your routes and an HttpKernel with your global middleware.
  3. serve starts a node:http server. For each incoming request it builds a Request and calls kernel.handle(request).
  4. The kernel runs the global middleware, matches a route, runs the route's middleware, calls your handler, and turns the result into a Response.
  5. The server writes the Response back to the client, and the kernel runs any "terminate" hooks.

Errors thrown anywhere in this chain are turned into responses by the exception handler, so the server always has something to send.

The entry point ​

In the generated web app, src/server.ts does the wiring. Trimmed to the essentials:

ts
import { env } from '@plinthjs/core'
import { HttpKernel, Router, securityHeaders, serve } from '@plinthjs/http'

import { createApplication } from '../src/bootstrap/app.js'
import { registerWebRoutes } from '../src/routes/web.js'

const app = await createApplication()

const router = new Router()
registerWebRoutes(router)

const kernel = new HttpKernel(router, {
  container: app,
  middleware: [securityHeaders({ hsts: false })],
})

await serve(kernel, Number(env('PORT', '3000')))

createApplication() (in src/bootstrap/app.ts) is shared with the console, so the web server and the command line boot the same way. It builds the Application, loads the config, and registers and boots every service provider. Because providers have already run when the kernel is built, everything they bound in the container is ready to resolve.

HttpKernel takes the router and three optional settings:

OptionPurpose
containerThe container used to create controller instances, and to look up the exception handler
middlewareThe global middleware stack, outermost first
exceptionHandlerAn ExceptionHandler instance (see below)

From Node to Plinth ​

serve(kernel, port) and createServer(kernel) are thin adapters over node:http. createServer returns a server without listening, which is useful if you want to call listen yourself, and serve also starts listening and resolves with the server. Each Node request goes through three steps:

  1. Request.fromNode reads and parses the request into an immutable Request. The body is buffered up to 1 MiB by default. If a request declares or sends a larger body, the server answers 413 Payload Too Large and closes the connection without running your application. Raise the limit with serve(kernel, port, host, { maxBodyBytes }).
  2. kernel.handle(request) produces a Response.
  3. The response is written to the socket. A streamed response is flushed chunk by chunk as its source yields; any other response is written in one go.

If something fails outside the kernel (for example a stream breaks after the headers were sent), the adapter cuts the connection, or answers a plain 500 if nothing was sent yet.

Because the kernel does not need a socket, you can run a request through your whole application in a test, with no server involved:

ts
import { HttpKernel, Request, Response, Router } from '@plinthjs/http'

const router = new Router()
router.get('/ping', () => Response.json({ pong: true }))

const kernel = new HttpKernel(router)
const response = await kernel.handle(new Request({ method: 'GET', url: '/ping' }))

response.status // => 200
response.body // => '{"pong":true}'

See Testing for more on this approach.

What the kernel does ​

handle runs these stages for every request:

  1. Global middleware, in the order you listed them, wrapping everything below.
  2. Route matching. The router matches the method, path, and host. No match is a 404, a path that exists for other methods is a 405 with an Allow header.
  3. Route middleware is resolved from the matched route and its group. Names such as 'auth' are looked up in the middleware aliases and groups registered on the router.
  4. Route middleware runs.
  5. Route-model binding. Just before the handler, any binding you registered with router.bind resolves the model. A binding that returns null or undefined is a 404.
  6. The handler runs and its result becomes a response.
  7. Terminable middleware runs after the response exists.

Global and route middleware ​

Middleware is a function that receives the request and a next function. It either calls next(request) to continue inward, or returns a response to stop. Code after await next(...) runs on the way back out:

ts
import type { Middleware } from '@plinthjs/http'

const timing: Middleware = async (request, next) => {
  const started = Date.now()
  const response = await next(request)
  return response.header('X-Response-Time', `${Date.now() - started}ms`)
}

The global stack is the outermost layer, so for a request that passes through global middleware A then B, and route middleware C, the order is A in, B in, C in, handler, C out, B out, A out. Here it is, traced:

ts
const trace: string[] = []
const wrap =
  (name: string): Middleware =>
  async (request, next) => {
    trace.push(`${name} in`)
    const response = await next(request)
    trace.push(`${name} out`)
    return response
  }

const router = new Router()
router
  .get('/', () => {
    trace.push('handler')
    return 'ok'
  })
  .middleware(wrap('route'))

const kernel = new HttpKernel(router, { middleware: [wrap('A'), wrap('B')] })
await kernel.handle(new Request({ method: 'GET', url: '/' }))

trace
// => ['A in', 'B in', 'route in', 'handler', 'route out', 'B out', 'A out']

Global middleware sees every request, including ones that matched no route, so a session or timing middleware can always do its work. Route middleware only runs for the routes it is attached to. The Middleware page covers writing, aliasing, and grouping it.

INFO

Route-model binding happens after route middleware runs, so a request that your auth middleware rejects never reaches a binding lookup and cannot learn whether a record exists. A middleware that needs the bound model itself should look it up on its own.

Handlers and controllers ​

A route handler is one of:

  • a function that receives the Request,
  • a [Controller, 'method'] pair,
  • a controller class on its own (an invokable single-action controller, which runs its __invoke method).

For the controller forms, the kernel asks the container for an instance of the class on every request, then calls the method with the request. That is how a controller can be registered in the container with its dependencies already wired:

ts
import { Application } from '@plinthjs/core'
import { Controller, HttpKernel, Request, Response, Router } from '@plinthjs/http'

class Greeter {
  hello(name: string): string {
    return `Hello, ${name}`
  }
}

class GreetingController extends Controller {
  private readonly greeter: Greeter
  constructor(greeter: Greeter) {
    super()
    this.greeter = greeter
  }

  show(request: Request): Response {
    return Response.json({ message: this.greeter.hello(request.param('name') ?? 'world') })
  }
}

const app = new Application()
app.singleton(Greeter, () => new Greeter())
app.bind(GreetingController, (container) => new GreetingController(container.make(Greeter)))

const router = new Router()
router.get('/greet/{name}', [GreetingController, 'show'])

const kernel = new HttpKernel(router, { container: app })
const res = await kernel.handle(new Request({ method: 'GET', url: '/greet/Ada' }))
res.body // => '{"message":"Hello, Ada"}'

Without a container, the kernel simply calls new Controller() with no arguments. See Controllers and The Service Container.

Turning results into responses ​

A handler can return a Response, or something simpler that the kernel converts for you:

Handler returnsResponse
a Responseused as is
a string200 with an HTML body
an object or array200 with a JSON body
null or undefined204 No Content
ts
router.get('/text', () => 'hello') // text/html
router.get('/data', () => ({ a: 1 })) // application/json
router.get('/nothing', () => null) // 204

For a HEAD request the kernel clears the body of whatever response was produced, so GET handlers answer HEAD automatically. See Responses.

Terminable middleware ​

A middleware can be an object with a handle function and a terminate function. terminate(request, response) runs after the response has been built, which is the place for work that should not delay the handler, such as saving a session or flushing buffers. Global middleware terminates first, then the matched route's middleware, and an error in one terminator does not stop the others:

ts
import type { TerminableMiddleware } from '@plinthjs/http'

const audit: TerminableMiddleware = {
  handle: (request, next) => next(request),
  terminate: async (request, response) => {
    await recordAudit(request.path(), response.status)
  },
}

Handling errors ​

The kernel renders errors inside the pipeline, not outside it. When a route is missing, a handler throws, or a route middleware throws, the ExceptionHandler turns the error into a Response and hands it back through next(). Global middleware therefore always receives a real response and can post-process it, which matters for middleware that must always run, such as the session middleware that saves state or a timing middleware that adds a header. If a global middleware itself throws, the kernel catches that too and renders it.

ts
const kernel = new HttpKernel(router, { middleware: [timing] })

const res = await kernel.handle(new Request({ method: 'GET', url: '/missing' }))
res.status // => 404
res.headers['X-Response-Time'] // => '1ms' (or similar): global middleware still ran

The exception handler ​

Every thrown error goes through two steps, report then render.

Rendering decides what the client sees:

  • An HttpException renders with its own status. NotFoundHttpException and MethodNotAllowedHttpException are provided; throw your own with new HttpException(418, "I'm a teapot").
  • Any error that carries a numeric status property is rendered with that status, and an errors property (a map of field to messages) is included. This is how validation failures become 422 and authorization failures become 403, without the HTTP package depending on them.
  • Anything else is a 500. With debugging off, the message is a generic "Internal Server Error", so internals never leak. With debugging on, the real message is shown.
  • If the request wants JSON (it sends an Accept header that asks for JSON, or X-Requested-With: XMLHttpRequest), the body is JSON such as { "message": "Not Found", "status": 404 }. Otherwise it is a small HTML error page.
  • A browser request that fails with an errors bag (a validation failure) is not rendered as a page. It becomes a redirect to the Referer (or /), with the errors and the old input flashed to the session, minus keys such as password. JSON requests get the 422 body instead.

Reporting sends the error somewhere you can see it. By default nothing is reported; you supply a sink. HttpException and its subclasses are not reported, since a 404 is not a bug. In the generated app, AppServiceProvider binds an ExceptionHandler whose sink writes to the logger:

ts
import { EXCEPTION_HANDLER, ExceptionHandler } from '@plinthjs/http'

app.singleton(EXCEPTION_HANDLER, () => {
  const handler = new ExceptionHandler(app.config.boolean('app.debug', false))
  handler.reportUsing((error) => logger.error(String(error)))
  return handler
})

The kernel picks its handler in this order: the exceptionHandler option, then whatever is bound in the container under EXCEPTION_HANDLER, then a new ExceptionHandler. The constructor argument is the debug flag.

Customising errors ​

The handler has hooks for each concern. They all chain:

ts
const handler = new ExceptionHandler(false)

// Convert one error type into another before reporting and rendering.
handler.map(PaymentError, () => new HttpException(503, 'Try again later'))

// Return your own response for some errors; return undefined to fall through.
handler.renderable((error) =>
  error instanceof NotFoundHttpException ? Response.json({ gone: true }, 404) : undefined,
)

// Reporting: extra callbacks, return false to stop further reporting.
handler.reportable((error) => !(error instanceof NoisyError))

// Do not report some error types (matches subclasses too).
handler.ignore(NoisyError)

// Set the log level for a type, and send reports to a sink.
handler.level(PaymentError, 'critical')
handler.reportUsing((error, context) => sendToLog(context['level'], error))

// Report each error instance at most once.
handler.withoutDuplicates()

// Replace the list of input keys never flashed back to a form.
handler.dontFlash(['password', 'password_confirmation', 'card_number'])

Mapping is applied first, so renderables, ignore, and levels all see the mapped error. In the example above, PaymentError becomes a 503 HttpException, which is then not reported because HttpException is on the ignore list. The Error Handling page goes deeper on each hook.

What to remember ​

  • One kernel runs the whole pipeline, and it needs no socket, so it is easy to test.
  • Global middleware wraps everything, including 404s and errors. Route middleware wraps a single route.
  • Controllers are resolved through the container on every request.
  • Route-model binding runs after route middleware, just before the handler.
  • Errors are rendered inside the pipeline, so middleware always gets a response back.

Released under the MIT License.