Creating file system routing in Bun

Creating file system routing in Bun

Bun has a built-in web server. However, handling requests with that web server is very rudimentary. So, I wanted to to create a simpler file-based routing system.

Initial approach

My initial approach was to require every file in the pages folder as a module.

While this worked for basic cases, it did not work for URLs with nested levels like /js/intro.

Slightly better approach

I then thought to replace any / with a specific character or set of characters like _____. However, if a user uses _____ in their path, this would return the equivalent but with /. Running a separate script to import all pages also didn't look clean.

The solution

I opened Bun's website and saw that they have an example called "File system routing". The example showed me that this was exactly what I wanted.

My final code looked like this:

const router = new Bun.FileSystemRouter({
  style: "nextjs",
  dir: "./pages/",

  fetch(req) {
    let match = router.match(req);
    let page = require(match.filePath);
    return new (page)(req, match.query, match.params);