How to Create a Server in Bun JS

Note that these instructions are for installing on Mac. Linux or WSL on Windows. Native Windows is experimental at this point (2023) so best to avoid it for now.

Open up a folder in VS Code where your project will live.

Open up a terminal within VS Code and enter:

npm install -g bun

This will install bun for global use on your system.

Spin up a new bun server:

bun init

This will create an index.ts file, package.json and a typescript config file with the bun standard settings.

Open up the index.ts file and paste in:

const server = Bun.serve({
  port: 3000,
  fetch(request) {
    return new Response("Welcome to Bun!");
  },
});

console.log(`Listening on localhost: ${server.port}`);

Now, in your terminal run the following command:

bun index.ts

Your server should now be running – as the console log message will tell you.

Open up a browser and go to: localhost:3000. You should see a ‘Welcome to Bun!’ message.

Finally, if you change some code in the index.ts file then you will need to quit the bun run time and restart it. However there is a handy watcher feature in bun. Instead of ‘bun index.ts’ now you can add in –watch:

bun --watch index.ts

This will reload the server (cold start) every time the file receives a change. Alternatively you can use the –hot flag to keep the server running and simply slot in the code you’ve changed.

bun --hot index.ts

The latter –hot version keeps the state of your server and any current connections so could come in quite handy!

Any question or clarifications? Please leave them in the comments!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *