Routing Mechanisms in Bun.js
0 117
๐ฃ๏ธ Routing Mechanisms in Bun.js: Organize Your APIs Like a Pro
Routing is the backbone of every web application โ itโs what helps your server know what to do when a user hits a specific endpoint. With Bun.js gaining popularity for its performance and simplicity, developers are eager to understand how to implement clean and efficient routing. In this blog, weโll explore the different routing mechanisms in Bun.js and how to build scalable route handlers.
๐ฆ What is Routing?
Routing is the process of mapping incoming requests to specific handler functions based on the URL and HTTP method. For example, a GET /users
route may fetch all users, while POST /users
may create a new one.
โก Bunโs Minimal Routing Approach
Unlike frameworks like Express, Bun.js doesn't come with a built-in router. Instead, routing can be implemented using native fetch()
handling or with lightweight custom logic. Hereโs a basic example:
// index.ts
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (req.method === "GET" && url.pathname === "/") {
return new Response("๐ Welcome to the home route!");
}
if (req.method === "GET" && url.pathname === "/about") {
return new Response("โน๏ธ About Bun.js Routing");
}
return new Response("โ Route not found", { status: 404 });
}
});
๐ Using a Route Table for Clean Code
To avoid a long list of if
statements, you can define your routes in a more organized way using a route map:
const routes = {
GET: {
"/": () => new Response("๐ Home Page"),
"/contact": () => new Response("๐ Contact Page")
},
POST: {
"/api": () => new Response("๐ Data received", { status: 201 })
}
};
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const handler = routes[req.method]?.[url.pathname];
if (handler) return handler();
return new Response("โ Route not found", { status: 404 });
}
});
This approach is scalable and easier to read, especially for larger projects.
๐งฑ Dynamic Routing (Path Params)
Bun doesnโt have built-in path parameters like /user/:id
, but you can implement it using pattern matching. Hereโs an example:
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const match = url.pathname.match(/^\/user\/(\d+)$/);
if (req.method === "GET" && match) {
const userId = match[1];
return new Response(`๐ค User ID: ${userId}`);
}
return new Response("โ Route not found", { status: 404 });
}
});
This allows you to handle routes like /user/123
manually.
๐ฆ Splitting Routes into Files
To keep your project clean, split routes into separate modules:
// routes/home.ts
export function homeRoute() {
return new Response("๐ This is home.");
}
// routes/about.ts
export function aboutRoute() {
return new Response("๐ About page.");
}
// index.ts
import { homeRoute } from "./routes/home";
import { aboutRoute } from "./routes/about";
const routes = {
GET: {
"/": homeRoute,
"/about": aboutRoute
}
};
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const handler = routes[req.method]?.[url.pathname];
if (handler) return handler();
return new Response("โ Not Found", { status: 404 });
}
});
๐ง Creating a Lightweight Router Utility
You can build a basic router class to encapsulate routing logic:
class Router {
routes = {};
get(path, handler) {
this.routes[`GET ${path}`] = handler;
}
post(path, handler) {
this.routes[`POST ${path}`] = handler;
}
handle(req) {
const url = new URL(req.url);
const key = `${req.method} ${url.pathname}`;
return this.routes[key]?.() || new Response("โ Route not found", { status: 404 });
}
}
const router = new Router();
router.get("/", () => new Response("๐ Home via Router"));
router.post("/submit", () => new Response("โ
Submitted"));
Bun.serve({
port: 3000,
fetch: (req) => router.handle(req)
});
This lets you scale your routes neatly with minimal boilerplate.
๐ Third-Party Router Options
If you prefer more abstraction, you can use third-party packages like elysia
(Bun-native web framework) or hono
(lightweight and works with Bun):
// Example with Elysia
import { Elysia } from "elysia";
new Elysia()
.get("/", () => "๐ก Home")
.get("/about", () => "โน๏ธ About")
.listen(3000);
๐ง Best Practices for Routing
- Group routes logically (e.g.,
/api/users
,/api/posts
) - Use proper HTTP methods (GET, POST, PUT, DELETE)
- Structure your code for readability and maintainability
- Log requests and errors for debugging
โ Conclusion
Bun.js may not come with a fancy router by default, but its simplicity allows you to build powerful and clean routing mechanisms from scratch. With just a few lines of code, you can handle static, dynamic, and even modular routes with clarity and speed.
So the next time you're building a Bun-based backend, remember โ routing is where your app's story begins! ๐งญ
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