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();
});
Syntax for .use() function

This middleware function has the ctx parameter, which represents the context objectIt contains information about the incoming HTTP request and the outgoing HTTP response., and 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   
}
})

Example code of Oak middleware function

Code explanation

  • In the src/deps.ts file, we added Oak’s import.

  • In the src/index.ts file, we import the createServer function and uses it to set up an HTTP server that listens on port 8000 with specific configurations.

  • In the src/web/index.ts file:

    • Line 1: Import the serve method from deps.ts.

    • Line 2: Import the Application class and instantiate it.

    • Lines 16–19: We will call the listen method and its event listener to log the application's running URL when it starts listening for incoming requests.

    • Lines 20–22: We add an error event 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 .use method 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

Copyright ©2025 Educative, Inc. All rights reserved