Setting Up an HTTP Server with Bun

09 January, 2024

JavascriptTypescriptProductivity

What is Bun?

Bun is a new Javascript runtime that focuses on simplicity, performance and developer experience. It has been built with the lessons from NodeJs in mind to minimise some of the common pitfalls of a Javascript runtime.
Bun has been built to minimise and abstract away a lot of the complexities from NodeJs to allow developers to focus on clean, maintainable, performant code.

Getting Started

  • Install Bun for your OS as per the official Bun instructions
  • Create a folder for your Bun project code files to live.
  • In a terminal for the new folder run bun init to set up the Bun project
  • Create an app.ts file in the folder

Creating the Bun Application

Open the app.ts file in your code editor of choice and add the following code:

const server = Bun.serve({ port: 3000, fetch(request) { return new Response("Welcome to Bun!"); }, }); console.log(`Listening on ${server.url}`);

If you are familiar with the Express framework, this should look very familiar.

This code snippet creates the bun app, sets up a basic response for the server, configures a port and starts the server.

Running the Server

Back in your terminal with the project folder open, run bun app.ts

In a browser, you can now navigate to http://localhost:3000 which will present you with the text 'Welcome to Bun!'

Conclusion

As shown above, the Bun framework provides a simple and effective way to create an HTTP server or API. This allows you to focus on writing clean, maintainable and performant code.

If you liked this post, please share it!