“The Application class coordinates managing the HTTP server, running middleware, and handling errors that occur when processing requests. Two of the methods are generally used: .use( ) and .listen( ). Middleware is added via the .use() method and the .listen( ) method will start the server and start processing requests with the registered middleware,” wrote the team developing Oak framework on their GitHub.
The backbone of any Oak application is the application object that is the instance of the Application class in the framework. It runs and manages the HTPP sever, middleware, and handle the error when processing requests. However, middleware is the core component in Oak application - it modifies request and response objects to obtain adequate result.
In Oak web framework, a middleware is a function in which the second parameter “next” is a special function used to pass the HTTP request to the next middleware in the HTTP request chain.
When used, the middleware receives two arguments for ctx and next parameters respectively. We can use any function as a middleware as long as this function has two parameters and it calls the next( ) function to pass the ctx object to the next middleware. To use any middleware, we must pass it as an argument to the use( ) method of the application object.
// app.js
import { Application } from "https://deno.land/x/oak/mod.ts"
const app = new Application()
app.use(async (ctx, next) => {
ctx.date = new Date()
await next()
})
app.use((ctx) => {
ctx.response.body = `Today is ${ctx.date}`
})
app.addEventListener(
"listen",
(e) => console.log("Listening on http://localhost:8000")
)
await app.listen({ port: 8000})
// denon run --allow-net app.js
The object automatically passed to ctx parameter has a number of other useful objects such as request, response, cookies that can be used in a variety of circumstances. In practice, we will use request and response objects almost in every middleware, and many data will be stored in the request objects.