01

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.

.env.local
1XFILES_API_KEY=xf_AbC12dEfGhIjKlMnOpQrStUvWxYz9012
2XFILES_PLATFORM_URL=https://platform.xfiles.dev

Origins: 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.

02

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.

app/api/xfiles-token/route.ts
1export async function POST() {
2 const user = await currentUser(); // your own auth
3 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 presence
9 scopes: ["search", "realtime", "messages", "notifications", "games"],
10 channels: { "orders:*": "s" }, // s subscribe · p publish · r presence
11 }),
12 });
13 return Response.json(await res.json(), { status: res.status }); // { token, expiresAt }
14}
userIdWho the token is for. Leave it out for an anonymous token (search and realtime only).
scopesAny of search realtime messages notifications games. Default: all five for a user.
channelsGrants on your own channels: { "orders:*": "s", "chat:lobby": "spr" }. Up to 50.
groupsGroups the user is in, for search documents shared with group:<id>.
nameA display name others see in presence. Never used to decide access.
ttlSecondsHow 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/tokensAPI key, serverMint a token. Refused from a browser.
GET/v1/auth/whoamianyWhat a key or token resolves to — handy while wiring things up.
03

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.

your server
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 one
21});
the browser
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 fine
6 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 typesstring, 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.
Visibilitypublic: anyone with a token, anonymous too. users: signed-in users. restricted (the default): each document's _access list — public, user:<id>, group:<id>.
WritesUp to 1,000 documents a request, all or nothing. Send your row's updatedAt as version, and retries and late writes are harmless.
Changing fieldsA 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.
FilesPUT /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/:nameAPI keyCreate or change a collection.
GET/v1/search/collections/:nameAPI keyIts settings, document count, and what is waiting to be indexed.
GET/v1/search/collectionsAPI keyEvery collection.
DELETE/v1/search/collections/:nameAPI keyThe collection and its documents.
POST/v1/search/collections/:name/documentsAPI keyAdd or replace documents: { documents, version? }.
POST/v1/search/collections/:name/documents/deleteAPI keyRemove documents: { ids }.
GET/v1/search/collections/:name/documentsAPI keyEvery stored document in id order: ?after=&limit= — to export, or compare with your database.
POST/v1/search/collections/:name/querytoken or keySearch.
POST/v1/search/querytoken or keyUp to 10 searches in one request: { searches: [{ collection, ... }] }.
POST/v1/search/collections/:name/rulesAPI keyPin or hide results for a query: { query, pinned: [{ id, position }], hidden: [id] }.
GET/v1/search/collections/:name/statsAPI keyTop queries, and the ones that found nothing.
POST/v1/search/collections/:name/reindexAPI keyRebuild the index from the stored documents.
PUT/v1/search/filesAPI keyTurn on search over the project's files.
04

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.

the browser
1let lastSeq; // the last persisted event seen
2const 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};
your server
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 elseTokens granted s subscribe, p publish, r join presence — { "orders:*": "s" }.
Catching upEvents 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.
PresenceSubscribe 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 with4401 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/realtimetokenThe WebSocket (wss://platform.xfiles.dev). Frames: auth sub unsub pub presence typing ping.
POST/v1/realtime/publishAPI keySend an event: { channel, event, data?, persist? }.
GET/v1/realtime/channels/:channel/historytoken or keyPersisted events after ?since= a sequence number.
GET/v1/realtime/presence/:channeltoken or keyWho is in a channel now.
GET/v1/realtime/healthAPI keyYour project's connections, users online and channels.
05

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.

the browser
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/conversationsuser or keyLatest 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/conversationsuser 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/:idkeyDelete a conversation for good: its messages, members and read positions. Attached files stay.
GET/v1/conversations/:idmember or keyThe conversation and its members' read positions.
POST/v1/conversations/:id/membersowner or keyAdd people to a group: { userIds }.
DELETE/v1/conversations/:id/members/:userIdowner, key, or selfRemove someone, or leave.
GET/v1/conversations/:id/messagesmember or key?after= or ?before= a sequence number — what you missed, or older history.
POST/v1/conversations/:id/messagesmember or key{ text?, data?, attachments?, clientId? }. Your server may post as a user (senderId) or as the system.
POST/v1/conversations/:id/readmemberMark read, up to now or a message.
GET/v1/conversations/:id/attachments/:fileId/urlmember or keyA link to an attached file.
PATCH/v1/messages/:idsender or keyEdit: { text }.
DELETE/v1/messages/:idsender, owner or keyDelete: the message keeps its place and loses its content.
06

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.

your server
1await platform("/v1/notifications", {
2 userIds: ["ana"],
3 type: "order.shipped", // users can turn types off, in-app or push
4 title: "Your order shipped",
5 body: "It arrives Thursday.",
6 url: "/orders/42",
7 dedupeKey: "order-42-shipped", // sent twice, shown once
8});

Push to browsers

  1. Download the service worker (https://www.xfiles.dev/xfiles-sw.js) and serve it from your own site at /xfiles-sw.js, with Cache-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.
  2. Ask from a click, never on page load, then send the subscription with the user's token:
the browser
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));
  1. On every page load, if permission is granted, send the subscription again: it can change, and so can who is signed in.
  2. On sign-out, POST /v1/notifications/subscriptions/remove with its endpoint, then unsubscribe in the browser.

Endpoints

POST/v1/notificationsAPI key{ userIds, type, title, body?, url?, data?, dedupeKey? }
GET/v1/notificationsuserThe user's list and unread count: ?unread=true.
POST/v1/notifications/:id/readuserMark one read — every tab hears it.
POST/v1/notifications/read-alluserMark all read.
GET/v1/notifications/preferencesuserPer type, and * for the rest: { inApp, push }.
PUT/v1/notifications/preferencesuserChange them.
GET/v1/notifications/vapid-public-keyanyoneThe key browsers subscribe to push with.
POST/v1/notifications/subscriptionsuserRegister this browser for push.
GET/v1/notifications/subscriptionsuserThe user's devices.
DELETE/v1/notifications/subscriptions/:iduserForget a device.
POST/v1/notifications/subscriptions/removeuserForget this browser by its endpoint.
07

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.

the browser
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 owner
9socket.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 }
Gamestictactoe (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 roomsOpen to the people invited and to the room's invite code (10 characters, shown to its owner). A room id alone opens nothing.
CommandsNumbered 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/gamestoken or keyThe games you can play.
GET/v1/games/roomstoken or keyOpen public rooms: ?game=.
POST/v1/games/roomsuser or key{ game, visibility?, maxPlayers?, config?, invite? } — your server names the owner with ownerUserId.
GET/v1/games/rooms/:idtoken or keyA room: seats, readiness, status.
POST/v1/games/rooms/:id/joinuserTake a seat: { inviteCode? }.
POST/v1/games/rooms/:id/leaveuserGive it up.
POST/v1/games/quickmatchuserA seat in an open public room, or a new room.
GET/v1/games/matches/:idplayer or keyA match's record: who played, the result, when.
08

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_requestNot valid — details says which field and why.
400 project_requiredAn organization key without X-XFiles-Project: name the project.
401 unauthorizedNo key or token, a wrong or expired one, a rotated key, or a token from before every token was ended.
402 payment_requiredYour 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 forbiddenThe token lacks the scope or channel grant, the origin is not allowed, or the route needs the API key.
403 suspendedThe account is suspended: every key and token is refused until that is lifted.
403 project_deletedThe project was deleted. It can be restored for 30 days; until then its key and tokens are refused.
404 not_foundAlso for what exists but is not yours — a conversation you are not in.
409 conflictThe room is full, the match has started, the message was deleted.
413 payload_too_largeMore than 256 KB in a request (8 MB when sending documents).
429 rate_limitedToo many: wait the Retry-After seconds.
503 unavailableSearch is briefly down (your writes are kept and indexed after), or the feature is not turned on.
Search200 requests a second per project and 20 per user; up to 10 searches a request; 1,000 documents a write.
Chat5 messages a second per user; text up to 10,000 characters; 10 attachments.
Live updates5,000 connections per project; 100 channels per connection; 30 messages a second per connection; 32 KB of data an event.
Multiplayer200 rooms per project; 20 commands a second per player.
NotificationsUp 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.

09

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 searchesEach search, from a browser or your server; a multi-search counts each query in it.
Search $0.10/1k documents/moDocuments 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 eventsEach 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-minutesEvery minute a WebSocket stays open — at least one per connection.
Chat $0.01/1k messagesEach message sent in a conversation.
Notifications $0.10/1k notificationsEach notification, to each user — in-app and web push included, however many devices.
Multiplayer $0.10/1k player-minutesEach 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.