kousaten

A simple JavaScript Trie-based HTTP router just routes.

Usage no npm install needed!

<script type="module">
  import kousaten from 'https://cdn.skypack.dev/kousaten';
</script>

README

kousaten

A simple JavaScript Trie-based HTTP router just routes.

  • Intuitive: Code is a UI and UX exists in libraries too.. so we try to keep kousaten as intuitive to JavaScript fundamentals as possible.
  • Light Weight: With zero dependencies kousten comes in at an extremely light 2KB before minification. Lack of dependencies also makes it a stable and secure choice.
  • Learn Once, Write anywhere: kousaten is an agnostic router that can be used with any technology stack; front or back.

Install

npm i kousaten
yarn add kousaten

Usage Example with Node HTTP/2

Note that Kousaten does not interact with the HTTP module directly at all. This means you can utilize Kousaten with any HTTP layer freely- or even in front-end applications.

const http2 = require('http2');
const fs = require('fs');
const Router = require('kousaten')

// Handlers
const testhandler = ({ req, resp }) => {
    console.log(req)
    resp.end("test");
};

const fallback = ({ resp }) => {
    resp.statusCode = 404;
    resp.end();
};

// Initiliaze the router. Accepts an object that contains options.
const router = new Router({
    trailingSlash: true, // Ignore trailing slashes in routes. Optional.
    fallback:fallback // Required option; define how the router should act when no route is found
});

// Register routes
router.add("/test", testhandler);

function onRequest(req, resp) {
    let ctx = { req, resp };
    let path = new URL(req.url, "https://localhost:3000").pathname
    
    // HTTP/2 will pass to the router on each request the path.
    // Use CTX to forward anything your handlers such as HTTP objects
    router.route(path, http);
}

const server = http2.createSecureServer({
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('crt.pem')
}, onRequest);

server.listen(8443);

Detailed Docs

  • To come