Deno API Server how to code the Middleware

Taka
2 min readMar 28, 2021

While developing Deno server, I struggled with the middleware implement, especially how to code the several middleware in the root file.

In this article, I code the error handler and logger example.

Version Infomation
deno 1.8.2 (release, x86_64-apple-darwin)
v8 9.0.257.3
typescript 4.2.2

middleware: oak@v6.5.0

log: https://deno.land/std@0.91.0/log/mod.ts

The bellows are the middleware files(error handler, logger examples) and app.ts(root file) examples.

errorHandler.ts

errorHandler.ts

Whenever an error is thrown, this middleware handles the error and responds the error object to a client.

More details about error handling, please check "Deno API Server — How to implement Error Handler by oak".

logger.ts

logger.ts

Whenever an error is thrown, this middleware handles the error log and responds the error object to a client.

The point of these middleware implementations is

  1. use async function
  2. use try-catch
  3. execute await next() in try part
  4. throwing error object in the last

app.ts

app.ts

Before executing logger middleware, set the logger level and format, etc.

setLogger function example is the bellow.

logger setting in logger.ts

The log format can be set in a handlers property. In loggers property, you can set the log level and configure some types of logs, for instance, dev mode and production mode.

To load the log configure, just call getLogger function in Deno std logger module. If you prefer prod loggers in the above, call getLogger(prod). Easy.

In my code, I call await setLogger(logLebel); for loading log config. Then execute app.use() middlewares.

Note that the middlewares are called from the top but they are executed from the bottom. The middleware for router should be called the last.

API Execution Result

When API throws an error in the controller or anywhere, the logger is called first then called error handler next.

You can put console.log in middleware and check how they are called.

--

--