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, we will register it and get to see it in action:
const responseTimer = async (ctx, next) => {
const { method, path } = ctx.request;
const start = Date.now();
await next();
const timeTaken = (Date.now() - start) / 1000; // divide by 1000 to get time in seconds
console.log(`${method} request to ${path} took ${timeTaken}s`);
};