Subscription APIs with Bun
0 106
๐ก Subscription APIs with Bun
Subscription APIs are a powerful way to keep clients updated in real time, especially in apps like chats, dashboards, or live tracking systems. With Bun, you can implement subscription APIs efficiently thanks to its lightning-fast performance and native WebSocket support. Let's dive into building real-time subscription APIs using Bun ๐.
๐ What is a Subscription API?
A Subscription API enables clients to receive data updates from the server automatically โ without polling. It's often powered by WebSockets, Server-Sent Events (SSE), or libraries like GraphQL Subscriptions.
In contrast to traditional REST APIs where the client makes a request, here the server can proactively send data when something changes ๐.
โ๏ธ Bun + WebSockets: The Real-Time Backbone
Bun supports websocket
natively via its Bun.serve()
function. Letโs build a simple subscription system that broadcasts messages to all connected clients ๐ข.
๐งช Basic WebSocket Server Example
const clients = new Set();
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("WebSocket Server is running");
},
websocket: {
open(ws) {
clients.add(ws);
console.log("๐ Client connected");
},
message(ws, message) {
console.log("๐จ Message received:", message);
for (const client of clients) {
if (client !== ws) client.send(message);
}
},
close(ws) {
clients.delete(ws);
console.log("โ Client disconnected");
}
}
});
This creates a simple chat-like subscription API. Every message received from a client gets broadcast to others in real time ๐.
๐ฅ Subscribing from the Client
const ws = new WebSocket("ws://localhost:3000");
ws.onmessage = (event) => {
console.log("๐ฌ New update:", event.data);
};
ws.onopen = () => {
ws.send("Hello from client!");
};
Once connected, the client receives any broadcast messages from the server. Instant updates, no polling, no hassle โก.
๐ง Use Cases for Subscription APIs
- ๐ฌ Real-time chat apps
- ๐ Live analytics dashboards
- ๐ฆ Order status tracking
- ๐ฎ Multiplayer game states
- ๐ฒ Push notifications for apps
๐งฐ Adding Context: Identifying Users
In real-world apps, we usually need to know whoโs connected. You can enhance the open
handler with headers or query params:
open(ws, req) {
const url = new URL(req.url);
const username = url.searchParams.get("user") || "anonymous";
ws.username = username;
console.log(`๐ ${username} connected`);
}
Now you can personalize subscriptions or filter messages per user.
๐ Securing Subscription APIs
Security is crucial in real-time systems. Hereโs how to harden your WebSocket setup:
- ๐ Authenticate users via tokens in headers or query params
- ๐ก๏ธ Sanitize all incoming messages
- ๐ Enforce message size limits
- โฑ๏ธ Implement heartbeat pings for idle timeouts
๐ Advanced: GraphQL Subscriptions in Bun
Want a GraphQL-style subscription layer? You can implement it using graphql-ws
with Bunโs WebSocket server. Hereโs a simplified idea:
import { useServer } from "graphql-ws/lib/use/ws";
import { WebSocketServer } from "ws";
const schema = buildSchema(`type Subscription { counter: Int }`);
let count = 0;
const server = new WebSocketServer({ port: 4000 });
useServer({
schema,
execute,
subscribe,
roots: {
Subscription: {
counter: {
subscribe: async function* () {
while (true) {
await Bun.sleep(1000);
yield { counter: ++count };
}
}
}
}
}
}, server);
Now your Bun app can serve proper GraphQL subscriptions โ ideal for frontend frameworks like Apollo or Relay ๐ฏ.
๐ฆ Message Queues & Subscriptions
You can even plug subscription events into queues like Redis Pub/Sub or Kafka to distribute updates across multiple servers for scale and resilience.
๐งช Testing Your Subscription API
For local testing, use tools like:
- ๐
wscat
โ WebSocket CLI for testing - ๐งช In-browser dev tools โ Inspect WebSocket frames
- ๐ Custom logging โ Log messages and events
๐ Wrapping Up
Subscription APIs add a powerful real-time layer to your Bun applications. With built-in WebSocket support and blazing speed, Bun makes building and scaling live updates easier than ever โก. Whether you're syncing live scores, updating dashboards, or chatting in real-time โ Bun has you covered.
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