Request Lifecycle

Introduction

The Node.js platform, in comparison of others, is asynchronous. It could be difficult in the beginning to understand everything about how it works and how you can handle this nature of Node.js.

It can also be easy to get confused with the JavaScript you write for your frontend and the one you write for your backend. They are the same in term of syntax, but they don’t run in the same run-time and context.

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

Request Flow

All HTTP requests you sent from a client (browser, mobile, etc.) are handled by Adonis Server module. It will execute all [server level middleware](), like the StaticFileMiddleware that serve all static file from the public directory.

If the request hasn’t been terminated by one of them, the Router of Adonis will come into play and try to find a route that matches the URL requested. If the Router cannot find a match, a RouteNotFound exception will be thrown.

After finding the route, global middleware are executed followed by named middleware that you’ve defined for this specific route. If none of then terminate the request, the route handler is called.

You must terminate the request in your route handler. When it’s done, Adonis will execute downstream middleware and send back the response to the client.

HTTP Context

Since Node.js handles HTTP requests concurrently, they need to be identified and managed uniquely. To help you do so, Adonis provide a 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 Provider or Middleware.

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

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

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