In the Deno Oak framework, serving both static content and dynamic routing simultaneously can be achieved by configuring Oak's middleware. Oak is a powerful middleware framework that enables you to handle HTTP requests and responses effortlessly. Below, I will provide an example demonstrating how to serve static files and handle dynamic routing requests within the same application.
1. Initialize Project and Dependencies
First, ensure you have installed Deno. Then, create a project directory and initialize the project. You can create a deps.ts file in the project's root directory to manage project dependencies:
typescript// deps.ts export { Application, Router, send } from "https://deno.land/x/oak/mod.ts";
2. Set Up Static File Service
Next, we can use Oak's send functionality to provide static file service. This can be implemented using a middleware that checks the request URL. If the request targets a file specified in the whitelist, it serves content from the file system.
typescript// staticMiddleware.ts import { send } from "./deps.ts"; export async function staticFileMiddleware(ctx: any, next: any) { const path = ctx.request.url.pathname; const fileWhitelist = ["/index.html", "/styles.css", "/script.js"]; if (fileWhitelist.includes(path)) { await send(ctx, path, { root: `${Deno.cwd()}/public`, index: "index.html", }); } else { await next(); } }
3. Create Dynamic Routes
Using Oak's Router, we can define dynamic routes to handle more complex requests. For example, we can create an API to return the current time:
typescript// router.ts import { Router } from "./deps.ts"; const router = new Router(); router.get("/api/time", (context) => { context.response.body = { time: new Date().toISOString() }; }); export default router;
4. Combine the Application
Finally, we integrate the static file service and route middleware into the Oak application. With this setup, the server can respond to both static file requests and API calls.
typescript// server.ts import { Application } from "./deps.ts"; import router from "./router.ts"; import { staticFileMiddleware } from "./staticMiddleware.ts"; const app = new Application(); // Use static file middleware app.use(staticFileMiddleware); // Use routes app.use(router.routes()); app.use(router.allowedMethods()); await app.listen({ port: 8000 });
5. Run the Server
Run the following command in the terminal to start the server:
bashdeno run --allow-net --allow-read server.ts
This approach allows your Deno Oak server to serve both static content and dynamic routing. By accessing different URLs, you can retrieve static pages or dynamically generated API responses. This method is ideal for building full-stack applications that incorporate both frontend and backend logic.