Middleware in Bun.js
0 1166
🧩 Introduction to Middleware in Bun.js
Middleware plays a crucial role in modern web development. It's the layer that sits between the incoming request and the final response—perfect for adding features like logging, authentication, error handling, or even modifying requests and responses.
With Bun.js being minimal and fast, you can implement middleware logic manually without a framework.
🛠️ What is Middleware in Bun.js?
Middleware in Bun.js refers to custom functions that intercept and process HTTP requests before sending a final response. While Bun doesn’t provide a built-in middleware system like Express, we can easily create one using JavaScript functions.
🧪 Simple Middleware Example
Let’s begin with a basic logger middleware that logs the incoming request path:
// logger.js
export async function logger(req) {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
}
Now let’s use this in our main server file:
// server.js
import { logger } from "./logger";
export default {
port: 3000,
async fetch(req) {
await logger(req);
return new Response("Middleware processed the request ✅");
}
};
This small setup logs every request before the response is sent. Clean, minimal, and Bun-native.
🔁 Chaining Multiple Middleware Functions
Want to process multiple middleware in sequence? You can build a small execution pipeline manually like this:
// auth.js
export async function auth(req) {
const authorized = req.headers.get("x-api-key") === "12345";
if (!authorized) {
return new Response("Unauthorized 🚫", { status: 401 });
}
}
// server.js
import { logger } from "./logger";
import { auth } from "./auth";
export default {
port: 3000,
async fetch(req) {
await logger(req);
const authResponse = await auth(req);
if (authResponse) return authResponse;
return new Response("Request passed middleware chain ✅");
}
};
Here, the auth middleware blocks unauthorized requests, while the logger records every request.
🧠 Middleware as Higher-Order Functions
To make things more modular, we can wrap handlers using middleware functions:
// middleware.js
export function withMiddleware(handler, ...middlewares) {
return async function (req) {
for (const mw of middlewares) {
const result = await mw(req);
if (result instanceof Response) return result;
}
return handler(req);
};
}
// server.js
import { logger } from "./logger";
import { auth } from "./auth";
import { withMiddleware } from "./middleware";
const handler = (req) => new Response("Final handler response 🎯");
export default {
port: 3000,
fetch: withMiddleware(handler, logger, auth)
};
Now, you can reuse this middleware system across multiple handlers with clean separation of concerns.
🔒 Use Cases for Middleware in Bun.js
- Authentication: Verify API keys or JWT tokens
- Logging: Track request metadata
- Rate Limiting: Block abuse by limiting traffic
- Input Validation: Ensure request structure is valid
- Error Handling: Catch and format runtime errors
📌 Middleware Tips for Bun.js
- Keep each middleware function focused and small
- Always return a
Responseobject if the request should stop - Use async/await to handle asynchronous tasks like DB checks
✅ Final Thoughts
Even though Bun.js doesn’t include a built-in middleware layer, you can create one effortlessly using simple JavaScript logic. This gives you full control, high performance, and no dependency overhead.
Whether you're building a REST API, a static file server, or a full-stack app—middleware is essential, and Bun.js gives you the tools to do it cleanly and efficiently.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments