Realtime

Subscribe to bucket data over WebSocket, receive inserts, updates and deletes as they happen, and write documents through the same connection.

Every bucket has a WebSocket endpoint that streams the result of a query and keeps it up to date. Use it for live feeds, dashboards, chat and collaborative screens.

Connect

Text
wss://api.example.com/api/bucket/<bucketId>/data?Authorization=<credentials>&filter=...&sort=...&limit=...&skip=...
Query parameterDescription
AuthorizationURL-encoded credentials, for example USER eyJhbGci... or APIKEY abc123.
filterAn expression (on MongoDB a JSON filter also works).
sortJSON sort object, for example {"created_at":-1}.
limit, skipWindow of documents to keep in the stream.

The caller needs the bucket:data:stream action on the bucket. For users, the bucket's read rule is applied to every message.

Messages from the server

Every message is a JSON object with a kind:

kindNamePayload
0Initialdocument: one document of the current result.
1End of initialThe initial result has been sent.
2Insertdocument: a document that entered the result.
3Deletedocument: a document that left the result.
4Expungedocument: a document removed because the window changed.
5Updatedocument: the new version of a document.
6Replacedocument: a replaced document.
7OrderThe order of documents changed.
8Responsestatus and message: the reply to a message you sent.
-1Errorstatus and message.
JSON
{"kind": 0, "document": {"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica"}, "views": 42}}
{"kind": 1}
{"kind": 5, "document": {"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica"}, "views": 43}}

Writing through the connection

Send {"event": ..., "data": ...} to insert, replace, patch or delete documents. Each message is answered with a kind: 8 response:

eventdataResponse
insertThe new document201 Created
replaceThe full document with _id200 OK
patch_id and the changed properties204 No Content
delete{"_id": "..."}204 No Content
JSON
{"event": "patch", "data": {"_id": "6b0b1972a5611972c29c25fd", "views": 45}}
JSON
{"kind": 8, "status": 204, "message": "No Content"}

Writes made this way go through the same validation, policies and rules as REST writes.

Example: a live list in the browser

JavaScript
const url = new URL(`wss://api.example.com/api/bucket/${BUCKET_ID}/data`);
url.searchParams.set("Authorization", `USER ${token}`);
url.searchParams.set("filter", 'document.status == "published"');
url.searchParams.set("sort", JSON.stringify({created_at: -1}));
url.searchParams.set("limit", "20");

const posts = new Map();
const socket = new WebSocket(url);

socket.onmessage = event => {
  const message = JSON.parse(event.data);
  switch (message.kind) {
    case 0: // initial
    case 2: // insert
    case 5: // update
    case 6: // replace
      posts.set(message.document._id, message.document);
      break;
    case 3: // delete
    case 4: // expunge
      posts.delete(message.document._id);
      break;
    case 1: // end of initial
      render([...posts.values()]);
      return;
  }
  render([...posts.values()]);
};

The bucket devkit does this bookkeeping for you and returns an RxJS observable of the current result:

TypeScript
import * as Bucket from "@spica-devkit/bucket";

Bucket.initialize({user: token, publicUrl: "https://api.example.com/api"});

const connection = Bucket.data.realtime.getAll(BUCKET_ID, {
  filter: 'document.status == "published"',
  sort: {created_at: -1},
  limit: 20
});

const subscription = connection.subscribe(posts => render(posts));
connection.patch({_id: postId, views: 45});

Tips

  • Keep limit small. The server tracks the window for every connection.
  • Reconnect when the socket closes. The devkit retries automatically on abnormal closures.
  • Use realtime for screens that change while users look at them. For one-off reads, REST is simpler and can be cached.