2

Now we can start a react App with bun as a server

Can we use Bunjs as complete backend server?

For Example, Can bun run this code?

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('hello world')
})

app.listen(3000)
Mohamed Kamel
  • 282
  • 2
  • 8

4 Answers4

2

I guess Bun does not YET implement all node.js api's. I tried http and it seems currently missing. And as much I understand it currently has its own built-in HTTP server.

Check the "Getting started" section on -> https://bun.sh/

A sample server:

    export default {
      port: 3000,
      fetch(request) {
        return new Response("Welcome to Bun!");
      },
    };

(This example reminds me of serverless functions.) As this is the case, it seems you can not rely on Node.js http, or most probably any server framework like express.

At least for now, bun's roadmap (https://github.com/oven-sh/bun/issues/159) shows a line, which I am not sure is talking about node's http server or sth. else about Bun's own server.

Once complete, the next step is integration with the HTTP server and other Bun APIs

Alper Batıoğlu
  • 313
  • 1
  • 2
  • 9
1

Other way is using Hono: https://honojs.dev/

There is a working demo: https://github.com/cachac/bun-api

  1. Import package and set new instance
import { Hono } from 'hono'
const app = new Hono()
  1. Create routes: Instead of NodeJs res.send(), use c.json({})
app.get('/hello', c => c.json({ message: 'Hello World' }))
  1. export and run api server:
export default {
  fetch: app.fetch,
  port: 3000
}
CACHAC
  • 29
  • 1
  • 2
1

Yes you can, and you don't even need an dependencies (like Express). Your example can be written as simply as:

Bun.serve({
  fetch() {
    return new Response('hello world');
  },
});
PORT=3000 bun index.js

See the Bun HTTP Docs for more server options like out-of-the box TLS support and WebSockets. Considering the benchmarks of Bun it's very capable as a backend server. Also see Elysia as a very complete Bun based backend framework that [on their homepage] claims to handle 17 x more request/second that Express.

MountainAsh
  • 428
  • 6
  • 12
0

Bun api is really different from nodejs, I created a library called bunrest, a express like api, so new user does not need to learn much about bun.

Here is how to use it

Install the package from npm

npm i bunrest

To create a server

const App = require('bunrest');
const server = new App.BunServer();

After that, you can call it like on express

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

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

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

To start the server

server.listen(3000, () => {
  console.log('App is listening on port 3000');
});
Jimmy lau
  • 173
  • 1
  • 8