Registering middleware in Koa is done with the .use() method found in the application object. To register the middleware defined in the previous section:
app.use(responseTimer);
Ensure you pass in the function reference when registering the middleware, and not call the function instead. A common mistake is to pass in responseTimer() instead of responseTimer.
Next, we can define and register a middleware to send a response back for every route as shown here:
// ...
app.use(async ctx => {
ctx.body = 'Hello World';
});
The complete application will look like this:
// koa-middleware.js
// initialize Koa
const Koa = require('koa');
const app = new Koa();
// create middleware function
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`);
};
// register middleware
app.use(responseTimer);
// send response back
app.use(async ctx => {
ctx.body = 'Hello World';
});
// start application
app.listen(1234, () => {
console.log('Server is running on port 1234')
});
Next, we can run the app with the following command:
node koa-middleware.js
Making a request to an endpoint on the application would produce logs such as this on your console:
GET request to / took 0.023s
GET request to /robots.txt took 0s