An express-like API for bun server

Overview

Logo

🧄 bunrest

NPM Version CodeFactor NPM Downloads

What is bunrest 👀

bunrest is an ExpressJs-like API for bun http server.

Features

  1. BLAZING FAST. Bun is super fast...

  2. 0️⃣ dependencies, work seamlessly with Bun

  3. 0️⃣ learning curve. If you know ExpressJs, you can start a bun server.

Table of Contents

Get started

To download bun

curl -fsSL https://bun.sh/install | bash

To create a bun project

bun init

This will create a blank bun project

see reference here

Server set up

Download the package

bun install bunrest
import server from "bunrest";
const app = server();

Usage

After that, you can write http method just like on express

app.get('/test', (req, res) => {
  res.status(200).json({ message: req.query });
});

app.put('/test/:id', (req, res) => {
  res.status(200).json({ message: req.params.id });
});

app.post('/test/:id/:name', (req, res) => {
  res.status(200).json({ message: req.params });
});

Router

The same as above, we create a router by calling server.Router()

After creation, we attach the router to server by calling server.use(your_router_reference)

// add router
const router = app.router();

router.get('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

router.post('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

router.put('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

app.use('/your_route_path', router);

Middlewares

We have two ways to add middlewares

  1. use : Simply call use to add the middleware function.

  2. Add middleware at the middle of your request function parameters.

// use
app.use((req, res, next) => {
  console.log("middlewares called");
  // to return result
  res.status(500).send("server denied");
});

app.use((req, res, next) => {
  console.log("middlewares called");
  // to call next middlewares
  next();
})

// or you can add the middlewares this way
app.get('/user', 
    (req, res, next) => {
      // here to handle middleware for path '/user'
    },
    (req, res) => {
      res.status(200).send('Hello');
    });

Error handling

To add a global handler, it's really similar to express but slightly different. The fourth argument is the error object, but I only get [native code] from error object, this might related to bun.

app.use((req, res, next, err) => {
    res.status(500).send('Error happened');
 });

At this time, if we throw an error on default path /

app.get('/', (req, res) => {
  throw new Error('Oops');
})

It will call the error handler callback function and return a response. But if we have not specified a response to return, a error page will be displayed on the browser on debug mode, check more on bun error handling

Start the server, listen to port

app.listen(3000, () => {
  console.log('App is listening on port 3000');
});

Request and Response object

To simulate the ExpressJs API, the default request and response object on bunjs is not ideal.

On bunrest, we create our own request and response object, here is the blueprint of these two objects.

Request interface

export interface BunRequest {
  method: string;
  request: Request;
  path: string;
  header?: { [key: string]: any };
  params?: { [key: string]: any };
  query?: { [key: string]: any };
  body?: { [key: string]: any };
  blob?: any;
}

Response interface

export interface BunResponse {
    status(code: number): BunResponse;
    option(option: ResponseInit): BunResponse;
    statusText(text: string): BunResponse;
    json(body: any): void;
    send(body: any): void;
    // nodejs way to set headers
    setHeader(key: string, value: any);
    // nodejs way to get headers
    getHeader();this.options.headers;
    headers(header: HeadersInit): BunResponse;
    getResponse(): Response;
    isReady(): boolean;turn !!this.response;
}

The req and res arguments inside every handler function is with the type of BunRequest and BunResponse.

So you can use it like on Express

const handler = (req, res) => {
  const { name } = req.params;
  const { id } = req.query;
  res.setHeader('Content-Type', 'application/text');
  res.status(200).send('No');
}

Next

Server rendering, websocket

Comments
  • Are there any solutions to solve the CORS problem?

    Are there any solutions to solve the CORS problem?

    Hi, Developers. Hope you are doing well. I am developing Restful API using bunrest framework. The problem I facing is CORS issue. I tried to solve the issue using cors npm like in express.js

    Here are some of my code snaps.

    import { Server } from 'bunrest' import cors from 'cors'

    const app = new Server(); app.use(cors());

    app.get('/api/endpoint', (req, res) => { // handler here )

    The errors I got is like this:

    if (Array.isArray(header)) { 149 | applyHeaders(header, res); 150 | } else if (header.key === 'Vary' && header.value) { 151 | vary(res, header.value); 152 | } else if (header.value) { 153 | res.setHeader(header.key, header.value); ^ TypeError: res.setHeader is not a function. (In 'res.setHeader(header.key, header.value)', 'res.setHeader' is undefined) at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:153:10) at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:149:10) at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:149:10) at cors (/home/legend/aib-bot/node_modules/cors/lib/index.js:187:6) at /home/legend/aib-bot/node_modules/cors/lib/index.js:224:16 at /home/legend/aib-bot/node_modules/cors/lib/index.js:214:14 at /home/legend/aib-bot/node_modules/cors/lib/index.js:219:12 at /home/legend/aib-bot/node_modules/cors/lib/index.js:199:8 at corsMiddleware (/home/legend/aib-bot/node_modules/cors/lib/index.js:204:6) at /home/legend/aib-bot/node_modules/bunrest/src/utils/chain.ts:7:12 at /home/legend/aib-bot/node_modules/bunrest/src/utils/chain.ts:19:23 at fetch (/home/legend/aib-bot/node_modules/bunrest/src/server/server.ts:1

    Please let me know how to fix the issue?

    Kindly Regards

    opened by tonychan524 4
  • `undefined is not an object (evaluating 'tree.get')` when using `app.router()`

    `undefined is not an object (evaluating 'tree.get')` when using `app.router()`

    Source:

    import server from 'bunrest'
    
    const app = server()
    const router = app.router()
    
    router.get('/', (req, res) => {
      res.status(200).json({ message: 'Router succeed' })
    })
    
    app.listen(3000, () => {
      console.log('App is listening on port 3000')
    })
    

    Error: undefined is not an object (evaluating 'tree.get') λ() node_modules/bunrest/src/server/server.ts:132:21

          async fetch(req1: Request) {
            const req: BunRequest = await that.bunRequest(req1);
            const res = that.responseProxy();
            const tree: TrieTree<string, Handler> =
              that.requestMap[req.method.toLowerCase()];
            const leaf = tree.get(req.path);
            /*          ^ happened here    */
    

    Stack trace:

    
      λ() node_modules/bunrest/src/server/server.ts:132:21
    

    Info:

    bun v0.2.2 macOS 13.2.0 (Apple Silicon) User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15 Pathname: /

    This works (no router):

    import server from 'bunrest'
    
    const app = server()
    
    app.get('/', (req, res) => {
      res.status(200).json({ message: 'Router succeed' })
    })
    
    app.listen(3000, () => {
      console.log('App is listening on port 3000')
    })
    
    opened by selfagency 2
  • Can't Have Hyphenated Route Names

    Can't Have Hyphenated Route Names

    I am running BunRest on Bun v0.1.13, and there seems to be an issue with the route names containing hyphens. All routes paths that start with the word before the hyphen and onwards on the hyphenated route will resolve to the hyphenated endpoint. Ex. if the '/api' route is requested, "hello world" with a status of 200 will be the response. The same for '/api-', '/api-e', '/api-en...', and '/api-endpoint-any-other-text-after_doesntneedtobehyphenated'.

    Code to reproduce this error:

    import server from "bunrest";
    
    const app = server();
    app.get('/api-endpoint', (request, response) => {
        response.status(200).json({message:"hello world!"});
    });
    app.get('/api', (request, response) => {
        response.status(500).json({message: "error!"});
    });
    
    app.listen(4000, () => {
        console.log('App is listening on port 3000');
    });
    

    console output:

    [davidn000@linux]$ bun buntest.js 
    App is listening on port 3000 
    
    opened by davidn000 2
  • Catch 404 request.

    Catch 404 request.

    Hi Developers,

    I would like to know if there is a way to catch bad requests?

    Let's say I have this code:

    import server from "bunrest";
    const app = server();
    
    app.get('/', (req, res) => {
        res.status(200).json({
            message: 'API Root'
        });
    });
    
    export default app;
    

    Obviously calling localhost:3000/ gives me {"message":"API Root"}.

    But if I try to reach a non-handled route (like localhost:3000/abcd), it gives me that: Welcome to Bun! To get started, return a Response object.

    Is there a way to catch bad requests as in express?

    Like in this example: https://expressjs.com/en/starter/faq.html by adding a middleware function at the very bottom of the stack (below all other functions):

    app.use((req, res, next) => {
      res.status(404).send("Sorry can't find that!")
    })
    

    Best Regards

    opened by LenoirRemi 2
  • dies on start + typescript errors

    dies on start + typescript errors

    when i try using bunrest following the directions in the readme, the app seems to just skip over bunrest and terminates:

    my code:

    import server from 'bunrest'
    
    const app = server()
    const router = app.router()
    
    router.get('/test', (req, res) => {
      res.status(200).json({ message: 'Router succeed' })
    })
    
    app.use((req, res, next, err) => {
      res.status(500).send('Error happened')
    })
    
    console.log('hello!')
    

    the result:

    » bun run src/index.ts
    hello!
    

    i tried compiling the typescript to see if that would work and this happened:

    12:51:58 AM » tsc src/**/*.ts
    node_modules/bunrest/src/router/router.ts:10:8 - error TS1259: Module '"path"' can only be default-imported using the 'esModuleInterop' flag
    
    10 import path from "path";
              ~~~~
    
      node_modules/@types/node/path.d.ts:178:5
        178     export = path;
                ~~~~~~~~~~~~~~
        This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
    
    node_modules/bunrest/src/server/response.ts:21:34 - error TS2339: Property 'json' does not exist on type '{ new (body?: BodyInit, init?: ResponseInit): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number): Response; }'.
    
    21         this.response = Response.json(body, this.options);
                                        ~~~~
    
    node_modules/bunrest/src/server/server.ts:33:14 - error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
    
    33   static get instance() {
                    ~~~~~~~~
    
    node_modules/bunrest/src/server/server.ts:118:12 - error TS2304: Cannot find name 'Bun'.
    
    118     return Bun.serve({
                   ~~~
    
    
    Found 4 errors in 3 files.
    
    Errors  Files
         1  node_modules/bunrest/src/router/router.ts:10
         1  node_modules/bunrest/src/server/response.ts:21
         2  node_modules/bunrest/src/server/server.ts:33
    
    opened by selfagency 1
  • Raw request body?

    Raw request body?

    Hi there, I was playing around with bunrest a bit for a weekend project and I've found myself in a situation where I need to access the raw request body. I'm not seeing anything immediately obvious in the docs, and trying to access things via req.request.body eventually end up with an error that Body is already used.

    Any ideas?

    opened by mmcc 1
  • [BUGFIX] Hyphenated route paths are now valid

    [BUGFIX] Hyphenated route paths are now valid

    Fixed an issue where hyphenated route names were not allowed. Introduced base64 encoding of routes so no conflicts happen with the new tilde delimiter (~) to separate route method with route path ie. GET-/api is now GET~L2FwaQ==.

    opened by davidn000 1
  • Typescript

    Typescript

    I got an error from typescript when i try to use it

    Cannot find module 'bunrest'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

    bun version: 0.1.13

    opened by zalnaRs 1
  • add: Type suggestion for ts

    add: Type suggestion for ts

    Hi, I liked the idea of using express like syntax on bun and really loved what you are doing here. I was using bunrest for a project and the type suggestions were not showing. So, I wanted to contribute to the project by adding the type hints.

    Would really love to see the project grow.

    opened by cinder-star 1
  • Bun installation

    Bun installation

    I need to install bun binaries to use this package right? Or simple package. Json file file with bun module will do the work? I wan to take risk using this in production for one of mu very mvp

    opened by rizwan92 1
Releases(version-1.1.2)
Owner
Rui.
Software engineer
Rui.
Fast, Bun-powered, and Bun-only(for now) Web API framework with full Typescript support.

Zarf Fast, Bun-powered, and Bun-only(for now) Web API framework with full Typescript support. Quickstart Starting with Zarf is as simple as instantiat

Zarf Framework 65 Dec 28, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A minimal routing library designed to sit on top of Bun's fast HTTP server.

siopao A minimal routing library designed to sit on top of Bun's fast HTTP server. Based on Radix Tree. Sio=Hot Pao=Bun Installation bun add siopao Us

Robert Soriano 69 Nov 8, 2022
Monolithic repo for api server, image server, web server

Onsecondary Market Deployed at https://market.onsecondary.com Monolithic repo for api server, image server, web server TODO -use a script to cull expi

Admazzola 2 Jan 11, 2022
A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Fabio Spampinato 9 Sep 17, 2022
WPPConnect/WA-JS API SERVER is a small api server to provide url preview for @wppconnect/wa-js library

WPPConnect/WA-JS API SERVER WPPConnect/WA-JS API SERVER is a small api server to provide url preview for @wppconnect/wa-js library Our online channels

null 13 Aug 11, 2022
🦆 lightning fast duckdb bindings for bun runtime

@evan/duckdb lightning fast duckdb bindings for bun runtime Install bun add @evan/duckdb Features ?? batteries included ?? jit optimized bindings ?? 4

evan 29 Oct 20, 2022
🚀 A boilerplate with generic configurations to a Nextjs project with bun, vitest, cicd and etc

?? Next.JS Template with Linter ?? Tools: NextJS Typescript ESLint (Code Pattern) Prettier (Formatter) Husky (Pre-commit) Vitest (Unit/Integration Tes

Rodrigo Victor 8 Dec 18, 2022
Fast, and friendly Bun web framework

?? KingWorld Fast, and friendly Bun web framework. ⚡️ Faster than Express.js by 8.5x on M1 Max Named after my favorite VTuber (Shirakami Fubuki) and c

SaltyAom 114 Jan 4, 2023
⚡️ A fast, minimalist web framework for the Bun JavaScript runtime

?? Bao.js A fast, minimalist web framework for the Bun JavaScript runtime. ⚡️ Bao.js is 3.7x faster than Express.js and has similar syntax for an easy

Matt Reid 746 Dec 26, 2022
Serve static files using Bun.serve or Bao.js

serve-static-bun Serve static files using Bun.serve or Bao.js. Currently in beta. Aiming for similar features as expressjs/serve-static. Install This

Jakob Bouchard 10 Jan 1, 2023
zx inspired shell for Bun/Node.

?? bnx zx inspired shell for Bun/Node. Install bun add bnx # npm install bnx Usage import { $ } from 'bnx' const list = $`ls -l` const files = list.

Robert Soriano 50 Oct 16, 2022
A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers

nbit A simple, declarative, type-safe way to build web services and REST APIs for Bun, Node and Cloudflare Workers. Examples See some quick examples b

Simon Sturmer 16 Sep 16, 2022
A blazingly fast Bun.js filesystem router, with an unpleasantly smooth experience!

Oily A blazingly fast Bun.js filesystem router, with an unpleasantly smooth experience! Installation · Usage · Examples · Discord Installation Once yo

Aries 22 Dec 19, 2022
Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Jarred Sumner 19 Dec 19, 2022
TypeScript type definitions for Bun's JavaScript runtime APIs

Bun TypeScript type definitions These are the type definitions for Bun's JavaScript runtime APIs. Installation Install the bun-types npm package: # ya

Oven 73 Dec 16, 2022
Detects which package manager (bun, pnpm, yarn, npm) is used.

@skarab/detect-package-manager Detects which package manager (bun, pnpm, yarn, npm) is used based on the current working directory. Features Support p

null 5 Sep 3, 2022