Architecture / Request

Request Lifecycle & Kernel

Understanding the Archery "request lifecycle" will give you a significant advantage when building your applications, allowing you to intercept and modify requests at the exact right moment.

The Entry Point

Your application's entry point is typically bin/server.dart. All requests that hit your HTTP server are directed to the Archery AppKernel.

The Kernel sits at the center of your application, deciding exactly how a given HTTP request should be handled. Let's break down the journey of a request.

  1. Bootstrapping the App: Before the first request is ever served, Archery initializes its singleton App container. This boots configurations, databases, core services, and user-defined ServiceProviders.
  2. Buffering the Request: When a request payload arrives, the Kernel immediately commands the FormRequest wrapper to buffer the request body. This prevents dreaded "stream already listened to" errors that are common in Dart when multiple middlewares attempt to inspect the request payload.
  3. Global Middleware Pipeline: The HTTP request then travels through a global array of middleware defined when you instantiate AppKernel. These middleware handle broad concerns like CORS and CSRF token generation.
  4. Router Dispatch: Assuming the request clears all global middleware, it is dispatched to the Router. If the route matches, any route-specific middleware is executed before your final Controller/Closure handler is invoked.

The Kernel Execution

If you look closely at your application's entry point, you will see how the AppKernel handles requests arriving from Dart's native HttpServer:

final appRouter = Router();
// Define routes on appRouter...

final kernel = AppKernel(
  middleware: [
    Cors.middleware,
    VerifyCsrfToken.middleware,
  ],
  router: appRouter,
);

final server = await HttpServer.bind('0.0.0.0', 8080);
print('Serving at http://${server.address.host}:${server.port}');

server.listen(kernel.handle);

By passing kernel.handle directly to server.listen(), you command the framework to funnel every raw HttpRequest directly into the Archery lifecycle pipeline.