WebSockets with Bun.js
0 119
🔌 WebSockets with Bun.js: Real-Time at Lightning Speed
Want to build real-time applications like chat systems, notifications, multiplayer games, or live dashboards? You’re in the right place. Bun.js isn’t just fast at running JavaScript — it also supports WebSockets for real-time, bidirectional communication with minimal setup. In this post, we’ll learn how to implement WebSockets with Bun.js using native APIs and Bun’s performance-oriented design.
⚙️ What Are WebSockets?
WebSockets provide a persistent, full-duplex communication channel between the client and server over a single TCP connection. Unlike HTTP, which is request-response-based, WebSockets allow servers to push data to clients instantly without waiting for a request.
🚀 Why Use Bun.js for WebSockets?
Here’s why Bun.js is an excellent match for WebSocket-based applications:
- Ultra-fast runtime built in Zig for performance
- Built-in WebSocket support using the WHATWG standard
- No external dependencies needed for simple use cases
- TypeScript support out-of-the-box
📁 Project Setup
Let’s start with a new Bun.js project:
mkdir bun-websockets
cd bun-websockets
bun init
This creates a package.json
and initializes your project.
🛠️ Creating a WebSocket Server
Bun doesn’t require an external library like ws
— it supports WebSockets natively inside the fetch
handler!
// index.ts
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) {
return undefined;
}
return new Response("WebSocket Server running", {
headers: { "Content-Type": "text/plain" },
});
},
websocket: {
open(ws) {
console.log("🔗 Client connected");
ws.send("👋 Welcome to the WebSocket server!");
},
message(ws, message) {
console.log("📩 Received:", message);
ws.send(`You said: ${message}`);
},
close(ws) {
console.log("❌ Client disconnected");
}
}
});
🌐 Testing with a WebSocket Client
You can test this setup using browser DevTools or a tool like wscat
:
npm install -g wscat
wscat -c ws://localhost:3000
You’ll receive the welcome message and can start chatting back and forth in real time.
📡 Broadcasting to All Clients
Let’s say you want to broadcast a message to all connected clients. You can track the clients in an array like this:
const clients: WebSocket[] = [];
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("WebSocket Server");
},
websocket: {
open(ws) {
clients.push(ws);
ws.send("👋 Connected!");
},
message(ws, message) {
for (const client of clients) {
if (client !== ws) {
client.send(`📢 Someone said: ${message}`);
}
}
},
close(ws) {
const index = clients.indexOf(ws);
if (index !== -1) clients.splice(index, 1);
}
}
});
💬 Sample Client in JavaScript
// client.html
<script>
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => {
console.log("Connected to Bun WebSocket");
ws.send("Hello from client!");
};
ws.onmessage = (event) => {
console.log("Server says:", event.data);
};
</script>
This client automatically connects, sends a message, and logs the response.
🔐 Security & Production Tips
- Use secure WebSockets (WSS) in production
- Implement authentication tokens during the upgrade request
- Limit message size to avoid abuse
- Use heartbeats/pings to detect dead connections
⚠️ Caveats and Things to Watch
Bun’s WebSocket support is rapidly improving, but keep these in mind:
- Doesn’t support all features from libraries like
ws
orsocket.io
- No built-in rooms or namespaces (yet)
- Reconnect logic must be handled manually in the client
Despite these, it’s fully capable for many real-time apps already!
✅ Final Thoughts
Building WebSockets with Bun.js is surprisingly simple and very performant. Whether you’re building a chat app, notification system, or game server, Bun offers a lightweight and fast environment to power it.
Give it a try and unlock real-time capabilities without the bloat. Bun keeps things lean, modern, and lightning quick 🚀.
💡 Bonus Tip: Use Bun with Frontend Frameworks
Want to integrate this WebSocket backend with frameworks like React, Vue, or Svelte? Just connect via standard WebSocket on the frontend and start pushing updates in real time — no backend bloat required!
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!

Share:
Comments
Waiting for your comments