What is the Oak middleware function?
Oak is a modern web framework built for Deno, which is a secure runtime for JavaScript and TypeScript. It facilitates web development and includes middleware functions that execute in a specific order between the request and response phases.
Middleware functions in Oak operate within the request-response cycle to modify or enhance the application's behavior. These functions follow their defined order and enable the application to perform diverse tasks such as request logging, error handling, authentication, and more.
The .use() method
The .use() method adds middleware functions to the application's middleware stack. The middleware functions are executed in the order as they were added using the .use() method.
app.use(async (ctx, next) => {/* Add code here for authentication, error handling or request logging */await next();});
This middleware function has the ctx parameter, which represents the next parameter, which is used to invoke the next middleware function.
Coding example
Run the application by clicking on the "Run" button and then type the following commands respectively.
deno run --allow-net src/index.ts
Open another terminal and type the following command to get a print statement:
curl http://localhost:8000/api
Here's an example of a basic Oak middleware function:
import { createServer } from "./web/index.ts";
createServer({
configuration: {
port: 8000
}
})
Code explanation
In the
src/deps.tsfile, we added Oak’s import.In the
src/index.tsfile, we import thecreateServerfunction and uses it to set up an HTTP server that listens on port 8000 with specific configurations.In the
src/web/index.tsfile:Line 1: Import the
servemethod fromdeps.ts.Line 2: Import the
Applicationclass and instantiate it.Lines 16–19: We will call the
listenmethod and its event listener to log the application's running URL when it starts listening for incoming requests.Lines 20–22: We add an
errorevent listener. This will be triggered if an error that hasn’t been handled occurs in our application.Lines 23–25: We create a simple piece of middleware. The
.usemethod registers a middleware function and sets the response body to "Running application from Oak middleware function," effectively changing the response content.Lines 28–29: We use these API routers to register our router in the main application.
Free Resources