Socket
Socket
Sign inDemoInstall

bun-serve-router

Package Overview
Dependencies
2
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    bun-serve-router

A very simple router implementation for `bun.serve()` using [URL Pattern API](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern).


Version published
Weekly downloads
1
decreased by-75%
Maintainers
1
Install size
52.7 kB
Created
Weekly downloads
 

Readme

Source

bun-serve-router

A very simple router implementation for bun.serve() using URL Pattern API.

No fancy, just works.

  • Supports URL patterns such as /user/:id
  • Using the standard API:

How to Use

Install the dependency:

bun add bun-serve-router

Import and add your routes:

import {Router} from "bun-serve-router";
const router = new Router();
router.add("GET", "/", (request, params) => {
    return new Response("Hello World!");
})

In the fetch handler of Bun.server(), you can match your routes like this:

const response = await router.match(request);

Since it is possible that no route matches, you should check if response is not undefined before returning it:

if (response) {
    return response;
}

Full Examples

import {Router} from "bun-serve-router";

const router = new Router();

// Add your routes
router.add("GET", "/", (request, params) => {
    return new Response("Hello World!");
})

Bun.serve({
    async fetch(request) {
        // Match here
        const response = await router.match(request);
        if (response) {
            return response;
        }

        // Return 404 if no route matches
        return new Response("404 Not Found", { status: 404 });
    },
});

Advanced Usage

Params

router.add("GET", "/hello/:myName", (request, params) => {
    return new Response("Hello " + params.myName);
})

URLPatternResult

The third parameter is the URLPatternResult object.

Check the URL Pattern API for more information.

router.add("GET", "/hello/:myName", (request, params, urlPatternResult) => {
    return new Response("Hello " + params.myName);
})

Others

It is actually a very standalone router. It is actually not limited to bun.serve(). As long as your application is using the Fetch API, it should be working too.

FAQs

Last updated on 26 Sep 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc