Create HTTP Server in Bun.js
×

Create HTTP Server in Bun.js

118

🌐 Introduction to HTTP Server in Bun.js

Bun.js isn't just a runtime—it's a full toolchain that includes a super-fast bundler, test runner, and built-in HTTP server capabilities. If you're looking to spin up a web server without installing external libraries like Express, Bun has you covered natively.

⚙️ Why Use Bun.js for Servers?

There are several reasons developers are turning to Bun.js for HTTP server development:

  • Blazing-fast performance thanks to JavaScriptCore
  • Zero dependencies needed for basic server logic
  • Built-in fetch-compatible request/response handling
  • Simple syntax that feels modern and clean

🚀 Creating Your First HTTP Server

Let’s dive into the simplest example of creating an HTTP server in Bun:

// server.js
export default {
  port: 3000,
  fetch(req) {
    return new Response("Hello from Bun!");
  }
};

This script creates a basic server that listens on port 3000 and returns a plain text response to any request.

🔍 Understanding the Code

  • port: The port your server listens on.
  • fetch(req): Bun’s native request handler that mimics the browser’s fetch API.
  • new Response(): Standard Web API response object.

You don't need Express, Fastify, or any external server libraries—just Bun’s built-in features.

🛠️ Handling Routes Dynamically

Let’s expand the server to respond differently based on the request path:

export default {
  port: 3000,
  fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === "/about") {
      return new Response("About Page");
    } else if (url.pathname === "/contact") {
      return new Response("Contact Page");
    } else {
      return new Response("Home Page");
    }
  }
};

This version of the server parses the URL and routes based on the pathname. It’s a lightweight approach that can be scaled into a full API.

🧪 Testing Your Bun Server

Run the server using:

bun server.js

Then open your browser and try:

  • http://localhost:3000/ → Home Page
  • http://localhost:3000/about → About Page
  • http://localhost:3000/contact → Contact Page

You’ll see different responses based on the route—just like a traditional framework but without the overhead.

🧵 Using JSON Responses

Want to build an API? Just return a JSON response like this:

export default {
  port: 4000,
  fetch(req) {
    const data = {
      message: "Hello from Bun API!",
      status: 200
    };

    return new Response(JSON.stringify(data), {
      headers: { "Content-Type": "application/json" }
    });
  }
};

⚡ Performance Tip

Because Bun is incredibly fast, your server will typically outperform the same app written in Node.js. However, remember to:

  • Use Bun’s native APIs
  • Avoid unnecessary dependencies
  • Test with real HTTP clients like Postman or curl

📦 Should You Use Bun for Production?

Bun is still under rapid development, but it’s quickly becoming production-ready for many types of apps. For internal tools, personal projects, microservices, or low-latency APIs—Bun is already a great fit.

✅ Final Thoughts

Creating an HTTP server with Bun.js is fast, minimal, and surprisingly powerful. With built-in support for fetch, Response, and routing, you can build everything from small utilities to RESTful APIs without reaching for external libraries.

As Bun matures, its server-side capabilities will only get better. Now is the perfect time to start experimenting!



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat