Deno nuggets: Oak middleware to log HTTP transaction

Mayank Choubey
Tech Tonic
Published in
May 19, 2022

--

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 a middleware that can log the HTTP transaction

Solution

To print details of the HTTP transaction, we need to write a logging middleware for Oak server. The logging middleware will call next() immediately, wait for it to finish, and then print the details from the request and response object. To print with color, we’ll use Deno’s standard library’s colors module.

Here is the code of the logging middleware:

Here is a round of testing using curl:

~: curl http://localhost:8000
~: curl http://localhost:8000/path1
~: curl http://localhost:8000/path1/path2
Hello Deno!
~: curl http://localhost:8000/path1/path2/path3
~:

Here are the logs:

--

--