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
wss://api.example.com/api/bucket/<bucketId>/data?Authorization=<credentials>&filter=...&sort=...&limit=...&skip=...| Query parameter | Description |
|---|---|
Authorization | URL-encoded credentials, for example USER eyJhbGci... or APIKEY abc123. |
filter | An expression (on MongoDB a JSON filter also works). |
sort | JSON sort object, for example {"created_at":-1}. |
limit, skip | Window 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:
kind | Name | Payload |
|---|---|---|
0 | Initial | document: one document of the current result. |
1 | End of initial | The initial result has been sent. |
2 | Insert | document: a document that entered the result. |
3 | Delete | document: a document that left the result. |
4 | Expunge | document: a document removed because the window changed. |
5 | Update | document: the new version of a document. |
6 | Replace | document: a replaced document. |
7 | Order | The order of documents changed. |
8 | Response | status and message: the reply to a message you sent. |
-1 | Error | status and message. |
{"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:
event | data | Response |
|---|---|---|
insert | The new document | 201 Created |
replace | The full document with _id | 200 OK |
patch | _id and the changed properties | 204 No Content |
delete | {"_id": "..."} | 204 No Content |
{"event": "patch", "data": {"_id": "6b0b1972a5611972c29c25fd", "views": 45}}{"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
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:
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
limitsmall. 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.