Defining middleware
Defining a middleware function in Koa involves creating an asynchronous function with two arguments—the context object (ctx), and the next method (next), which invokes the next middleware function to be called. This is similar to the way middleware functions are defined in Express. One major difference in their approach is that Koa implements the context object in place of the individual request (req) and response (res) objects provided by Node. Another difference is that Koa makes use of the async... await paradigm in place of callback functions.
Let's define a simple middleware to log how long it takes our application to process requests. In the following code block, we define a middleware function, and in the next section, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access