You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.

Request Lifecycle

Introduction

The Node.js platform is asynchronous. For beginners, it can be difficult to understand how it works, and how to handle its non-blocking approach to application flow.

It can also be confusing differentiating the JavaScript you write for your front-end verses the JavaScript you write for your backend. They are the same in terms of syntax, but don’t run in the same run-time and context.

Having an excellent high-level overview of the request lifecycle is a must-have. AdonisJs will feel less “magical”, and you will be more confident about building your applications.

Request Flow

HTTP requests sent from a client are handled by the AdonisJs Server module, executing all server level middleware (for example, the StaticFileMiddleware that serves static files from the public directory).

If the request isn’t terminated by server level middleware, the AdonisJs Router comes into play. It attempts to find a route that matches the URL requested. If Router cannot find a match, a RouteNotFound exception will be thrown.

After finding a matching route, all global middleware are executed followed by any named middleware defined for the matched route. If no global or named middleware terminate the request, the matched route handler is called.

You must terminate the request in your route handler. Once terminated, AdonisJs executes all downstream middleware and sends the response back to the client.

HTTP Context

AdonisJs provides a HTTP Context object to each route handler.

This object contains everything you need to handle the request, like the request or response class, and can be easily extended via Providers or Middleware:

start/routes.js
Route.get('/', ({ request, response, view }) => {
  // request
  // response
  // view
})

Alternatively, you can use it directly instead of unpacking it:

start/routes.js
Route.get('/', (ctx) => {
  // ctx.request
  // ctx.response
  // ctx.view
  // etc
})