Skip to main content

Usage with Bun

Bun is a toolkit for JavaScript and TypeScript development, allowing you to run, build, test, and debug a full-stack application.

For examples of projects, please refer to these resources: Bun or Bun TypeScript.

Initialization

1. Set up an entry point:

// 1. Import node-file-router
import { initFileRouter } from 'node-file-router';

// 2. Initialize the main request handler
const useFileRouter = await initFileRouter();

// 3. Start serving server and attach request handler to fetch
const server = Bun.serve({
port: 3123,
fetch: (req) => useFileRouter(req)
});

console.log(`Listening on http://localhost:${server.port}`);

2. Override the default 404 handler:

├── api/
│ └── _404.js
...
export default function NotFound() {
return new Response('404');
}

Handlers Implementation

Basic Handler

Bun operates with a Response object that should be returned. Therefore, the API handlers look like the following:

├── api/
│ └── products.js
...
export default function ProductsRoute(req) {
return new Response('products');
}

Request and Response

├── api/users
│ └── [id].js
...

Since we have a response on return, the route params object is the second argument.

const db = {
13: { id: '13', name: 'Dan' }
}

export default {
async put(req, routeParams) {
db[routeParams.id] = await req.json();

return new Response(
JSON.stringify(db[routeParams.id]),
{ headers: { 'Content-Type': 'application/json' } }
);
}
}

Middlewares Implementation

For detailed information, please refer to the Middlewares Section. Generally, the interface can be described as follows:

export default function useMyMiddleware(req, next) {
// Code before
// ...

await next(); // <-- The router's code or next middleware (on nested levels)

// ...
// Code after
}