Subscription APIs with Bun
×


Subscription APIs with Bun

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!


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