How it fits
The platform runs beside the files API at https://platform.xfiles.dev. Your server talks to it with the project's API key, as it does to the files API. Browsers never see that key: your server mints them a short-lived token for one user, and the browser uses the token for search, live updates, chat, notifications and games.
1XFILES_API_KEY=xf_AbC12dEfGhIjKlMnOpQrStUvWxYz90122XFILES_PLATFORM_URL=https://platform.xfiles.devOrigins: The API key works from a browser only on the project's allowed origins (Keys & access) — keep it on your server. Tokens are checked against the same list when there is one; with an empty list a token works from any origin. Origins match exactly (scheme, host and port: https://www.shop.example is not https://shop.example), with no wildcards. Removing an origin closes WebSockets from it within 90 seconds, and stops push to browsers that subscribed there.
Rotating: Tokens don't depend on the key, so rotating it leaves your users signed in to live updates and chat. When the tokens may have leaked too, end them all — tick "Also end every user token" when rotating, or POST /api/v1/projects/{id}/revoke-tokens: they stop within a minute, and WebSockets opened with them close within 90 seconds (4401), so your pages fetch fresh ones.
Many sites, one key: Running many sites or customers? Give each its own project: its search, channels, chat, notifications and rooms never meet another's, and it has its own limits and usage. Your server holds one organization key (xfo_…) instead of a key per project. It mints tokens and calls every route here as any project of its organization: add X-XFiles-Project: <project id>, and on the WebSocket send project in the auth frame. See Organizations on the REST API tab.
Every route: This page shows how to use each feature and lists its routes. The complete reference — every field, frame and limit, written for coding assistants too — is /llms.txt, part 3.
Tokens
One route on your server, called by your pages. A user token lasts an hour by default (24 hours at most); one without a userId is anonymous: it can search and listen to public: channels, nothing else, and can last up to 90 days. Ask for a new one a minute before expiresAt.
1export async function POST() {2 const user = await currentUser(); // your own auth3 const res = await fetch(`${process.env.XFILES_PLATFORM_URL}/v1/auth/tokens`, {4 method: "POST",5 headers: { Authorization: `Bearer ${process.env.XFILES_API_KEY}`, "Content-Type": "application/json" },6 body: JSON.stringify({7 userId: user.id,8 name: user.name, // shown in presence9 scopes: ["search", "realtime", "messages", "notifications", "games"],10 channels: { "orders:*": "s" }, // s subscribe · p publish · r presence11 }),12 });13 return Response.json(await res.json(), { status: res.status }); // { token, expiresAt }14}userId | Who the token is for. Leave it out for an anonymous token (search and realtime only). |
scopes | Any of search realtime messages notifications games. Default: all five for a user. |
channels | Grants on your own channels: { "orders:*": "s", "chat:lobby": "spr" }. Up to 50. |
groups | Groups the user is in, for search documents shared with group:<id>. |
name | A display name others see in presence. Never used to decide access. |
ttlSeconds | How long it lasts: 30 seconds to 24 hours for a user (default 1 hour), up to 90 days for anonymous (default 24 hours). |
Endpoints
| POST | /v1/auth/tokens | API key, server | Mint a token. Refused from a browser. |
| GET | /v1/auth/whoami | any | What a key or token resolves to — handy while wiring things up. |
Search
Describe a collection once, send documents whenever your data changes, and query from the browser with a token: typo tolerance, prefixes, filters, facets and sorting. Documents are searchable within a second or two. Watch a collection, try queries and pin results on the dashboard's Search page.
1const platform = (path, body, method = "POST") =>2 fetch(`${process.env.XFILES_PLATFORM_URL}${path}`, {3 method,4 headers: { Authorization: `Bearer ${process.env.XFILES_API_KEY}`, "Content-Type": "application/json" },5 body: JSON.stringify(body),6 });7
8await platform("/v1/search/collections/products", {9 visibility: "public", // or "users", "restricted"10 fields: [11 { name: "title", type: "string", weight: 3 },12 { name: "brand", type: "string", facet: true },13 { name: "price", type: "float", sort: true },14 { name: "inStock", type: "bool", filter: true },15 ],16}, "PUT");17
18await platform("/v1/search/collections/products/documents", {19 documents: [{ id: "1", title: "Wireless keyboard", brand: "Acme", price: 49, inStock: true }],20 version: 1762257600000, // your row's updatedAt in ms: an older write never replaces a newer one21});1const res = await fetch("https://platform.xfiles.dev/v1/search/collections/products/query", {2 method: "POST",3 headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },4 body: JSON.stringify({5 query: "keybord", // typos are fine6 filters: { inStock: true, price: { lt: 100 } }, // also: ["a", "b"], { gte, lte }, { or: [...] }, { near }7 sort: "price:asc",8 facets: ["brand"],9 }),10});11const { hits, total, facets } = await res.json(); // hits[i].highlights.title.snippet has <mark>s| Field types | string, string[], int, float, bool, date, geo, int[], float[] — mark each facet, filter or sort as you need; strings are searchable, with a weight of 1–10. |
| Visibility | public: anyone with a token, anonymous too. users: signed-in users. restricted (the default): each document's _access list — public, user:<id>, group:<id>. |
| Writes | Up to 1,000 documents a request, all or nothing. Send your row's updatedAt as version, and retries and late writes are harmless. |
| Changing fields | A change the index cannot take in place rebuilds it in the background; searches keep answering from the old one until the new one is ready. |
| Files | PUT /v1/search/files makes the project's own files searchable: names, tags and descriptions from their metadata, and the text of TXT, Markdown, CSV and JSON files. |
Endpoints
| PUT | /v1/search/collections/:name | API key | Create or change a collection. |
| GET | /v1/search/collections/:name | API key | Its settings, document count, and what is waiting to be indexed. |
| GET | /v1/search/collections | API key | Every collection. |
| DELETE | /v1/search/collections/:name | API key | The collection and its documents. |
| POST | /v1/search/collections/:name/documents | API key | Add or replace documents: { documents, version? }. |
| POST | /v1/search/collections/:name/documents/delete | API key | Remove documents: { ids }. |
| GET | /v1/search/collections/:name/documents | API key | Every stored document in id order: ?after=&limit= — to export, or compare with your database. |
| POST | /v1/search/collections/:name/query | token or key | Search. |
| POST | /v1/search/query | token or key | Up to 10 searches in one request: { searches: [{ collection, ... }] }. |
| POST | /v1/search/collections/:name/rules | API key | Pin or hide results for a query: { query, pinned: [{ id, position }], hidden: [id] }. |
| GET | /v1/search/collections/:name/stats | API key | Top queries, and the ones that found nothing. |
| POST | /v1/search/collections/:name/reindex | API key | Rebuild the index from the stored documents. |
| PUT | /v1/search/files | API key | Turn on search over the project's files. |
Live updates
One WebSocket per tab carries channels, presence, chat and games. Authenticate in the first message, never in the URL; you are subscribed to user:<id> automatically. When a token is close to expiring, send auth again with a new one — the connection stays open.
1let lastSeq; // the last persisted event seen2const socket = new WebSocket("wss://platform.xfiles.dev/v1/realtime");3socket.onopen = () => socket.send(JSON.stringify({ type: "auth", token }));4socket.onmessage = (m) => {5 const frame = JSON.parse(m.data);6 if (frame.type === "ready") socket.send(JSON.stringify({ type: "sub", id: "1", channel: "orders:42", since: lastSeq }));7 if (frame.type === "evt") { lastSeq = frame.seq ?? lastSeq; console.log(frame.channel, frame.event, frame.data); }8};1await platform("/v1/realtime/publish", {2 channel: "orders:42",3 event: "shipped",4 data: { carrier: "DHL" },5 persist: true, // kept 7 days: a reconnecting client catches up with { since: seq }6});user:<id> | That user only. Notifications and chat invitations arrive here. |
public:<name> | Anyone with a token for the project, anonymous too. Published by your server, or by tokens granted p. |
conversation:<id> | A conversation's members. Published by chat. |
| anything else | Tokens granted s subscribe, p publish, r join presence — { "orders:*": "s" }. |
| Catching up | Events published with persist: true carry a seq. Subscribe again with since after a reconnect: what you missed arrives first, then live events — no gap, no duplicate. Other events are best effort. |
| Presence | Subscribe with presence: true to see who is here (joins, leaves); only then can you send typing. A reload is not a leave: a user stays present for 3 seconds. |
| Closed with | 4401 token invalid, expired or revoked, or the key was rotated — mint a new one. 4402 your account is out of credit — it reconnects after a top-up. 4403 not allowed, from an origin you removed, the account is suspended, or the project was deleted. 4429 too many messages. 1012 the server is restarting — reconnect. |
Endpoints
| GET | /v1/realtime | token | The WebSocket (wss://platform.xfiles.dev). Frames: auth sub unsub pub presence typing ping. |
| POST | /v1/realtime/publish | API key | Send an event: { channel, event, data?, persist? }. |
| GET | /v1/realtime/channels/:channel/history | token or key | Persisted events after ?since= a sequence number. |
| GET | /v1/realtime/presence/:channel | token or key | Who is in a channel now. |
| GET | /v1/realtime/health | API key | Your project's connections, users online and channels. |
Chat
Direct and group conversations, ordered messages that post once however often they are retried, read positions and attachments. Members hear new messages on conversation:<id>; anyone who was away gets one notification per burst of unread messages, not one per message.
1const call = (path, body) => fetch(`https://platform.xfiles.dev${path}`, {2 method: "POST",3 headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },4 body: JSON.stringify(body),5}).then((r) => r.json());6
7const { conversation } = await call("/v1/conversations", { kind: "direct", members: ["bob"] });8await call(`/v1/conversations/${conversation.id}/messages`, { text: "hello", clientId: crypto.randomUUID() });9await call(`/v1/conversations/${conversation.id}/read`, {});Attachments: Upload with the files API from your server, with ownerUserId set to the sender, then send the file ids as attachments. Members fetch a private file's link from the conversation; it lasts 15 minutes.
Endpoints
| GET | /v1/conversations | user or key | Latest first. A token: its own, with unread counts. The key: every conversation in the project (a team inbox), or ?member= one user's. Pass next back as before. |
| POST | /v1/conversations | user or key | { kind: "direct" | "group", members, title?, createdBy? } — one direct conversation per pair. From the key without createdBy, the first member owns it. Not for a token minted with startConversations: false. |
| DELETE | /v1/conversations/:id | key | Delete a conversation for good: its messages, members and read positions. Attached files stay. |
| GET | /v1/conversations/:id | member or key | The conversation and its members' read positions. |
| POST | /v1/conversations/:id/members | owner or key | Add people to a group: { userIds }. |
| DELETE | /v1/conversations/:id/members/:userId | owner, key, or self | Remove someone, or leave. |
| GET | /v1/conversations/:id/messages | member or key | ?after= or ?before= a sequence number — what you missed, or older history. |
| POST | /v1/conversations/:id/messages | member or key | { text?, data?, attachments?, clientId? }. Your server may post as a user (senderId) or as the system. |
| POST | /v1/conversations/:id/read | member | Mark read, up to now or a message. |
| GET | /v1/conversations/:id/attachments/:fileId/url | member or key | A link to an attached file. |
| PATCH | /v1/messages/:id | sender or key | Edit: { text }. |
| DELETE | /v1/messages/:id | sender, owner or key | Delete: the message keeps its place and loses its content. |
Notifications
Your server sends; each user has an in-app list that updates live, and browsers that allowed it get a push notification even when your site is closed. Users choose which types they get, in-app and as push.
1await platform("/v1/notifications", {2 userIds: ["ana"],3 type: "order.shipped", // users can turn types off, in-app or push4 title: "Your order shipped",5 body: "It arrives Thursday.",6 url: "/orders/42",7 dedupeKey: "order-42-shipped", // sent twice, shown once8});Push to browsers
- Download the service worker (
https://www.xfiles.dev/xfiles-sw.js) and serve it from your own site at/xfiles-sw.js, withCache-Control: no-cache. A push subscription belongs to the site that made it, so each site serves its own copy. It shows the notification and opens its link on click — only links on your site. - Ask from a click, never on page load, then send the subscription with the user's token:
1async function enablePush(token) {2 if ((await Notification.requestPermission()) !== "granted") return;3 const reg = await navigator.serviceWorker.register("/xfiles-sw.js");4 await navigator.serviceWorker.ready;5 const { publicKey } = await fetch("https://platform.xfiles.dev/v1/notifications/vapid-public-key").then((r) => r.json());6 const sub = (await reg.pushManager.getSubscription())7 ?? (await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: base64UrlToBytes(publicKey) }));8 await fetch("https://platform.xfiles.dev/v1/notifications/subscriptions", {9 method: "POST",10 headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },11 body: JSON.stringify(sub.toJSON()), // { endpoint, keys }12 });13}14
15const base64UrlToBytes = (s) =>16 Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=")), (c) => c.charCodeAt(0));- On every page load, if permission is granted, send the subscription again: it can change, and so can who is signed in.
- On sign-out,
POST /v1/notifications/subscriptions/removewith itsendpoint, then unsubscribe in the browser.
Endpoints
| POST | /v1/notifications | API key | { userIds, type, title, body?, url?, data?, dedupeKey? } |
| GET | /v1/notifications | user | The user's list and unread count: ?unread=true. |
| POST | /v1/notifications/:id/read | user | Mark one read — every tab hears it. |
| POST | /v1/notifications/read-all | user | Mark all read. |
| GET | /v1/notifications/preferences | user | Per type, and * for the rest: { inApp, push }. |
| PUT | /v1/notifications/preferences | user | Change them. |
| GET | /v1/notifications/vapid-public-key | anyone | The key browsers subscribe to push with. |
| POST | /v1/notifications/subscriptions | user | Register this browser for push. |
| GET | /v1/notifications/subscriptions | user | The user's devices. |
| DELETE | /v1/notifications/subscriptions/:id | user | Forget a device. |
| POST | /v1/notifications/subscriptions/remove | user | Forget this browser by its endpoint. |
Multiplayer
Rooms, seats and an authoritative simulation for browser games: the server validates every move against the state it changes. Rooms are made and found over HTTP; the game itself is played over the same WebSocket, with game.* messages. A player who drops keeps their seat for 30 seconds and gets the whole state back on rejoining.
1const { games } = await fetch("https://platform.xfiles.dev/v1/games", { headers: { Authorization: `Bearer ${token}` } }).then((r) => r.json());2const { room } = await call("/v1/games/rooms", { game: "tictactoe", visibility: "private", invite: ["bob"] });3// or take a seat in an open public room, or open one:4const { room: open } = await call("/v1/games/quickmatch", { game: "tictactoe" });5
6socket.send(JSON.stringify({ type: "game.join", id: "j1", room: room.id }));7socket.send(JSON.stringify({ type: "game.ready", id: "r1", room: room.id, ready: true }));8socket.send(JSON.stringify({ type: "game.start", id: "s1", room: room.id })); // the owner9socket.send(JSON.stringify({ type: "game.cmd", room: room.id, seq: 1, cmd: { cell: 4 } }));10// ← game.room · game.state { tick, state } · game.reject { seq, reason } · game.over { result }| Games | tictactoe (turn-based), skirmish (real-time, each player sees their own view) and skirmish-lockstep (every tick's commands, for many units). GET /v1/games lists them. |
| Private rooms | Open to the people invited and to the room's invite code (10 characters, shown to its owner). A room id alone opens nothing. |
| Commands | Numbered with an increasing seq; up to 20 a second per player, 2 KB each. A refused one comes back as game.reject. |
Endpoints
| GET | /v1/games | token or key | The games you can play. |
| GET | /v1/games/rooms | token or key | Open public rooms: ?game=. |
| POST | /v1/games/rooms | user or key | { game, visibility?, maxPlayers?, config?, invite? } — your server names the owner with ownerUserId. |
| GET | /v1/games/rooms/:id | token or key | A room: seats, readiness, status. |
| POST | /v1/games/rooms/:id/join | user | Take a seat: { inviteCode? }. |
| POST | /v1/games/rooms/:id/leave | user | Give it up. |
| POST | /v1/games/quickmatch | user | A seat in an open public room, or a new room. |
| GET | /v1/games/matches/:id | player or key | A match's record: who played, the result, when. |
Errors and limits
Errors answer { "error": "a sentence", "code": "for programs" }, with details when a request is not valid. Every response carries an X-Request-Id: quote it when something goes wrong.
400 bad_request | Not valid — details says which field and why. |
400 project_required | An organization key without X-XFiles-Project: name the project. |
401 unauthorized | No key or token, a wrong or expired one, a rotated key, or a token from before every token was ended. |
402 payment_required | Your account has been out of credit for more than 7 days, or has never had any. Search, live updates, chat, notifications and multiplayer are paused until you add credits — then they resume within a minute, with the same keys. Your dashboard's platform pages say so, and count down the 7 days before. |
403 forbidden | The token lacks the scope or channel grant, the origin is not allowed, or the route needs the API key. |
403 suspended | The account is suspended: every key and token is refused until that is lifted. |
403 project_deleted | The project was deleted. It can be restored for 30 days; until then its key and tokens are refused. |
404 not_found | Also for what exists but is not yours — a conversation you are not in. |
409 conflict | The room is full, the match has started, the message was deleted. |
413 payload_too_large | More than 256 KB in a request (8 MB when sending documents). |
429 rate_limited | Too many: wait the Retry-After seconds. |
503 unavailable | Search is briefly down (your writes are kept and indexed after), or the feature is not turned on. |
| Search | 200 requests a second per project and 20 per user; up to 10 searches a request; 1,000 documents a write. |
| Chat | 5 messages a second per user; text up to 10,000 characters; 10 attachments. |
| Live updates | 5,000 connections per project; 100 channels per connection; 30 messages a second per connection; 32 KB of data an event. |
| Multiplayer | 200 rooms per project; 20 commands a second per player. |
| Notifications | Up to 1,000 users a request; a title of 200 characters and a body of 1,000. |
SDK: A TypeScript SDK wraps all of this — token refresh, reconnects that miss nothing, typeahead search, an InstantSearch adapter, and game sessions. It is being prepared for npm; until then, everything above works with plain fetch and WebSocket from any language.
Pricing
Paid from the same prepaid balance as files, for what you use and nothing else. Each day (UTC) is billed once it is over, as one line in Billing; the Billing page shows this month so far. A connection is billed by its minutes (at least one), a match by its players' minutes, a document while it is kept, and a push as part of its notification. At a zero balance the platform keeps working for 7 days, then pauses until a top-up (402 payment_required) — at once for an account that has never had credit.
| Search $0.10/1k searches | Each search, from a browser or your server; a multi-search counts each query in it. |
| Search $0.10/1k documents/mo | Documents kept in your collections, charged by the day: a day costs the monthly rate divided by the days in that month. |
| Live updates $1.00/1M events | Each event published on a channel — by your server, by a browser, and the ones chat and notifications publish to deliver live. |
| Live updates $1.00/1M connection-minutes | Every minute a WebSocket stays open — at least one per connection. |
| Chat $0.01/1k messages | Each message sent in a conversation. |
| Notifications $0.10/1k notifications | Each notification, to each user — in-app and web push included, however many devices. |
| Multiplayer $0.10/1k player-minutes | Each player's minutes in a match, counted when it ends. |
Building with an AI assistant?
Point it at the complete reference, or connect the MCP server so it can read these docs and use your project.