Deno nuggets: Oak middleware to measure response time
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to write an Oak middleware that can measure the HTTP response time?
import { Application } from "https://deno.land/x/oak/mod.ts";const app = new Application();app.use((ctx) => {
ctx.response.body = "Hello World!";
});await app.listen({ port: 8000 });
Solution
The HTTP request processing time can be measured by adding a middleware that will take a time reading before and after calling the next handler. It’s best to measure the timing using high resolution performance APIs.
Here is an Oak middleware for the above ‘Hello world!’ application:
The time diff can then be logged on console, or recorded into files/database/GA/etc.
To use high resolution time, — allow-hrtime permission is required
The application can be tested like this:
> curl http://localhost:8000
> curl http://localhost:8000
> curl http://localhost:8000> deno run --allow-net --allow-hrtime app.ts
Time taken: 0.06770800000003874
Time taken: 0.03862499998649582
Time taken: 0.013624999992316589