Skip to content
DeveloperMemos

Using Oak to Create a HTTP Server in Deno

Deno, Oak, HTTP Server1 min read

Deno is a secure runtime for JavaScript and TypeScript, built on top of V8, Rust, and Tokio. It includes a built-in set of standard modules, such as fs and http, which make it easy to write server-side code. However, if you want to build a more complex web application, you'll likely need a more robust framework. That's where Oak comes in. Oak is a middleware framework for Deno that makes it easy to create HTTP servers and middleware. In this article, we'll walk through the process of using Oak to create a simple HTTP server in Deno.

Creating a Basic HTTP Server

To create an HTTP server using Oak, we need to create an instance of the Application class, add some middleware, and start listening for requests. Here's an example:

1import { Application } from "https://deno.land/x/oak/mod.ts";
2
3const app = new Application();
4
5app.use((ctx) => {
6 ctx.response.body = "Hello, world!";
7});
8
9await app.listen({ port: 8000 });

In this example, we import the Application class from Oak, create a new instance of it, and add a middleware function that sets the response body to "Hello, world!". Finally, we call the listen() method on the application instance to start listening for incoming requests on port 8000.

Handling Different HTTP Methods

In addition to handling basic GET requests, we can also use Oak to handle other HTTP methods, such as POST, PUT, and DELETE. To do this, we can use the Router middleware to define routes and handlers for each method. Here's an example:

1import { Application, Router } from "https://deno.land/x/oak/mod.ts";
2
3const app = new Application();
4
5const router = new Router();
6
7router.get("/", (ctx) => {
8 ctx.response.body = "This is a GET request!";
9});
10
11router.post("/", (ctx) => {
12 ctx.response.body = "This is a POST request!";
13});
14
15app.use(router.routes());
16app.use(router.allowedMethods());
17
18await app.listen({ port: 8000 });

In this example, we import both the Application and Router classes from Oak. We create a new instance of each, and define two routes: one for GET requests and one for POST requests. Each route has a corresponding handler function that sets the response body to a message indicating which method was used. Finally, we add the router middleware to the application using the routes() and allowedMethods() methods.

Conclusion

By using middleware and defining routes, we can create complex web applications with ease. Oak provides a simple and intuitive API for working with HTTP requests and responses, making it an excellent choice for building APIs and web servers in Deno. Happy coding!