Developer guide

Everything an app can talk to

A pocket server is a small HTTP server with a filesystem, some GPIO pins and a WebSocket. Apps are HTML files you upload to it. They talk to the endpoints below from plain fetch(), or through pocket.js, one file that wraps them — no build step, no npm install.

Still settling This API is under active development. Endpoints, response shapes and error codes can still change between firmware releases — nothing here is frozen yet. If you’re building something you mean to keep working, note the api and firmware versions that GET /version reports for the board you tested against, and give this page another read after you update it.

The basics

Everything is served from the device itself. The address is http://pocket.local, on the device’s own network and on a home network alike; on the device’s own network http://192.168.4.1 reaches it when mDNS does not resolve on your machine.

  • An app is a folder on the card with an index.html in it. Its other files — stylesheets, scripts, images, the data it saves — sit in the same folder, and the device serves them as they are: there is no build step.
  • Keep everything the app needs in its folder. On the device’s own network there is no internet, so a stylesheet or a script fetched from a CDN never arrives. The owner can join the device to a home network instead, and there a CDN may well work; an app that depends on one works only there.
  • Once the folder is on the device, the app and the API share an origin, so there is no CORS to configure.
  • There are two ways to talk to the device, and both reach the same endpoints: pocket.js, which names files relative to the app’s folder and turns refusals into readable messages, or plain fetch() against the endpoint reference.

pocket.js

pocket.js is a library that does what every app on the device would otherwise repeat: it finds the app’s folder, calls the endpoints below on the app’s behalf, and turns every refusal into a sentence a person can read. It is one file with no dependencies, and the same copy ships with every example on the apps page.

Download pocket.js and put it beside index.html. The file is ES5 and needs only fetch and Promise, so it runs in the captive-portal browser a phone opens when it joins the device’s network.

<script src="pocket.js"></script>
<script>
  Pocket.readJson('entries.json', []).then(render);
</script>

How every call behaves

Every function that talks to the device returns a Promise. A call the device accepted resolves with the result the table gives. A call the device refused rejects with an Error whose message is a sentence: on a 401 the sentence says what needs the owner, and on any other refusal the sentence is the device’s own reason, or the HTTP status when the device gave none. The library never touches the page. Put err.message where the person will see it.

Pocket.write('entries.json', entries)
  .then(function () { status.textContent = 'Saved.'; })
  .catch(function (err) { status.textContent = err.message; });
// "Saving entries.json needs the owner of this device. Sign in as the owner, or ask them to allow it."

Every request carries an X-Requested-With header, so a 401 reaches your code instead of opening the browser’s own password box. Every file name and folder is percent-encoded for you; pass plain names.

Files

Each function takes a file name and an optional folder, dir. The folder defaults to the app’s own, Pocket.folder, which is "/guestbook" for a page served at /guestbook/ and "/" at the top level. Pass a folder only to reach outside the app’s own.

FunctionResolves with
Pocket.folderThe app’s own folder, as a string. A property, not a call.
Pocket.url(name)A relative URL for one of the app’s own files, for an img.src or a link.
Pocket.list(dir, opts)The folder’s entries: {name, size} for a file, {name, dir: true} for a folder. In the app’s own folder the files that are the app (index.html, app.json, .app-overrides.json, pocket.js) are left out; pass {all: true} to include them.
Pocket.read(name, dir)The Response, for .text(), .json() or .blob(), or null when the file does not exist yet. The request bypasses the browser cache.
Pocket.readJson(name, fallback, dir)The file parsed as JSON, or fallback when the file is absent or is not JSON.
Pocket.readText(name, fallback, dir)The file as a string, or fallback when the file is absent.
Pocket.write(name, data, dir)Creates or overwrites the file. data may be a Blob or File, a string, or any other value, which is sent as JSON.
Pocket.writeVerified(name, text, dir)Writes the string, reads the file back, and rejects if the two differ, so a save that was cut off cannot leave a truncated file for the next visitor.
Pocket.remove(name, dir)Deletes the file, or the folder and everything in it.
Pocket.mkdir(name, dir)Creates an empty folder. The parent must exist.
Pocket.storage(){total, used, free} in bytes, and media: the card or the onboard flash. Check free before a large upload.
// A guestbook: load the entries, add one, save.
var entries = [];
Pocket.readJson('guestbook.json', []).then(function (list) { entries = list; render(); });

form.onsubmit = function (e) {
  e.preventDefault();
  entries.push({ name: nameField.value, message: messageField.value, when: Date.now() });
  Pocket.write('guestbook.json', entries)
    .then(render)
    .catch(function (err) { note.textContent = err.message; });
};

// A photo gallery: show every image in the folder.
Pocket.list().then(function (files) {
  files.forEach(function (f) {
    if (!/\.(jpe?g|png|gif|webp)$/i.test(f.name)) return;
    var img = document.createElement('img');
    img.src = Pocket.url(f.name);
    grid.appendChild(img);
  });
});

// An upload from a file input, then a delete.
Pocket.write(input.files[0].name, input.files[0]);
Pocket.remove('old-photo.jpg');

Pins

The pins are closed to guests until the owner allows them for the app from the admin page, and the rejection says so. The pin numbers and the body shape are those of GET and POST /pin/{n} below.

FunctionResolves with
Pocket.pin.read(n){pin, value}, the pin’s level as the device reads it.
Pocket.pin.write(n, body){pin, value} after the change. body is {mode, value}; either key may be left out.
Pocket.pin.write(2, { mode: 'OUTPUT', value: 1 })
  .catch(function (err) { status.textContent = err.message; });
// "Controlling the pins needs the owner of this device. Sign in as the owner, or ask them to allow it from the app's folder on the admin page."

Pocket.pin.read(2).then(function (state) { light.textContent = state.value ? 'On' : 'Off'; });

The WebSocket

Pocket.socket(onMessage, onStatus) opens the broadcast socket and returns a handle. Every text anyone sends reaches every connected page, the sender included, so a page renders its own message when the message comes back rather than guessing. The socket reconnects on its own while the page is open; onStatus, when given, receives 'open', 'reconnecting' or 'closed'.

HandleDoes
sock.send(text)Sends the text. Returns true, or false when the socket is not open at that moment.
sock.close()Closes the socket and stops the reconnecting.
var sock = Pocket.socket(function (text) {
  var msg = JSON.parse(text);
  addLine(msg.who + ': ' + msg.said);
}, function (state) {
  banner.textContent = state === 'open' ? '' : 'Reconnecting…';
});

sock.send(JSON.stringify({ who: name, said: input.value }));

The device and the app’s own rules

FunctionResolves with
Pocket.version(){api, supports, firmware, limits}, as GET /version reports.
Pocket.requires(api)The same, or rejects with a message naming both versions when the firmware’s API version is older than api. Advisory: the device never refuses an app for its version.
Pocket.apps()Every app on the card with its resolved rules, as GET /apps reports.
Pocket.app()This app’s own entry: its title and its paths with the effective role per verb, or null when the folder has no manifest.
Pocket.allows(verb)true when the app’s rules let a guest do 'read', 'browse', 'upload' or 'delete' at its top level. Also true when the answer is unknown, which is the right guess: try, and show the rejection.
// Hide the delete buttons before a guest tries one.
Pocket.allows('delete').then(function (ok) { toolbar.hidden = !ok; });

Pocket.requires(2).catch(function (err) { note.textContent = err.message; });
// "This app needs firmware with API version 2; this device is at 1. Update the firmware from pocket-servers.com/update.html."

The owner

A page can sign in as the owner. After signIn every later call from that page is signed with the password, so a path the manifest keeps for the owner opens and a write the owner kept for themselves goes through. The password lives in the page’s memory only: reload, and it is gone. The sign-in uses the device’s own digest helper, /auth/digest.js, which is loaded on first use.

FunctionResolves with
Pocket.signIn(password)true, or rejects with "That password didn't work."
Pocket.signOut()Nothing. Later calls are unsigned again.
Pocket.isOwner()true while the page is signed in. Synchronous.
form.onsubmit = function (e) {
  e.preventDefault();
  Pocket.signIn(password.value)
    .then(function () { return Pocket.readJson('admin/report.json', null); }) // "read": "owner" in app.json
    .then(showReport)
    .catch(function (err) { status.textContent = err.message; });
};

The Owner page example is this flow in full, and the app author’s guide says what a finished app does with a refusal.

The manifest, app.json

A folder with an app.json in it is an app. The file tells the device which API version the app was written for, what to call it, and what a guest may do in each part of the folder. The device reads the file when the card is scanned and after every write to the folder, and GET /apps reports what the device made of it.

{
  "api": 1,
  "title": "Pirate box",
  "gpio": false,
  "paths": {
    "/": {
      "browse": "everyone",
      "upload": "everyone",
      "delete": "everyone"
    },
    "/private/":  { "read": "owner" },
    "/notes.txt": { "upload": "owner" }
  }
}

Keys

KeyType and meaning
apiInteger, required, at least 1. The lowest API version the app needs. Declare the version of the device you tested on; GET /version reports it. Without this key the manifest is unusable.
titleString, optional, up to 40 characters. Shown on the admin page and by launchers. Defaults to the folder name.
gpioBoolean, optional. true asks for the pins. A request, not a grant: the pins stay closed to guests until the owner allows them from the admin page.
pathsObject, optional. Each key is a path inside the folder and each value is an object mapping a verb to the lowest role that may do it. The rules below.

Any other key is ignored. A manifest that is not valid JSON, lacks api, or names a verb or role the firmware does not know is unusable: the folder is listed by GET /apps with an error naming the fault, and the app grants nothing, never part of what it asked for. The unknown-word case is reported as compat: "ahead", which is also what the device reports for an api newer than its own, since both mean the app was written for something newer.

Paths

A key is a path inside the app’s folder. The key starts with /, is at most 32 characters, and cannot contain ... A key that ends in / covers the folder it names and everything beneath; any other key is one exact file. "/" is the app’s whole folder.

VerbCoversDefault
readOpening a page or a file.everyone
browseListing the folder with GET /files.owner
uploadAdding or overwriting a file, and making a folder.owner
deleteDeleting a file or a folder.owner

The roles are everyone, anyone on the network, and owner, whoever holds the password. For a request, the device picks the longest key that covers the path and takes the verb’s role from that one rule. A verb the rule leaves out gets the default, not a shorter key’s answer: "/private/": {"read": "owner"} keeps uploads in /private/ for the owner whatever "/" says about them. An app that keeps no files needs only api.

Four files are the owner’s to write whatever the manifest says: app.json, .app-overrides.json and index.html in the app’s folder, and /.settings.json at the root. Deleting an app’s folder outright is the owner’s too. The words moderator, user and $user are reserved for a future identity design and are refused today.

The owner’s overrides, .app-overrides.json

The owner can narrow or widen what an app asked for without editing the app. The admin page writes .app-overrides.json beside app.json, in the same grammar: a paths object, and gpio, which here is the grant. Where the owner’s file names a path and verb the manifest also named, the owner’s value wins; where it names a new path, a rule is added. Both files travel with the card. The merged result, with every default filled in, is what GET /apps and Pocket.app() report; an app reads its own entry to hide a control a guest cannot use.

{ "gpio": true, "paths": { "/": { "delete": "owner" } } }

Limits

LimitESP32-S3ESP8266
Apps per card326
paths keys per app, overrides merged in86
One paths key32 characters
Folder name24 characters
title40 characters
Manifest or overrides file2 KB

A device reports its own first two limits in GET /version. A folder past the app cap is listed by GET /apps with ignored: true and behaves as a plain folder until an app is deleted; a folder whose name is over the cap is never an app. The app author’s guide says what a finished app does with these rules.

Endpoint reference

If you would rather not use pocket.js, or you want to see what the library does for you, the endpoints are plain HTTP: files, pins, the WebSocket, and the admin page’s own controls. Three things hold for all of them.

  • Paths are absolute from the storage root: /photos/trip.jpg, not photos/trip.jpg. pocket.js builds these from the app’s folder and the name you give it.
  • A failure comes back as {"error": "…"} with a sentence you can show someone. A few routes answer plain text, so check response.ok before r.json(). Any endpoint can answer 401 (sign in), 403 (nobody has claimed this device), 429 (too many wrong passwords) or 500 (storage trouble); an entry lists only the codes specific to it.
  • Reading files, the pins and the WebSocket need no password, as far as the app’s rules allow. The admin endpoints need the owner’s password once one is set, except the entries marked public. The curl examples sign with --digest; the js examples are bare fetch() calls, so from a page sign them with Pocket.signIn() first.

Passwords & guests

A device has to be claimed before it does anything. Out of the box it’s in setup mode: it serves its setup page at /, answers GET /auth/status, GET /auth/digest.js and POST /auth/claim, and refuses everything else with 403 and {"setupRequired": true}. Setting a password there claims it, and the device starts serving normally.

From then on the Admin endpoints need that password — add --digest -u admin:yourpassword to curl, or just use the admin page. The device uses HTTP digest auth, so a browser will prompt for it on its own. A 401 carries the challenge to sign with — in WWW-Authenticate normally, or in X-Auth-Challenge if your request sent an X-Requested-With header, which is how an app keeps the browser from putting its own password box over it. One marked stale=true means only the nonce aged out: re-sign the same request rather than asking the user again. Five requests in a row signed with the wrong password and the device stops accepting them for up to a minute (429, with a Retry-After); a correct one clears it, and so does a reboot.

There are two roles and one password. owner is whoever holds it; everyone is anyone on the network. What a guest may do is not a device setting: it is decided per folder by the app that lives there, in its app.json, as narrowed by the owner’s .app-overrides.json beside it. Both travel with the card. The verbs are read, browse, upload and delete; anything a manifest doesn’t mention defaults to read for everyone and the rest for the owner, so the root of a card and any folder without a manifest are read-only to guests. The manifest has the grammar.

Four files are the owner’s to write whatever a manifest says — app.json, .app-overrides.json and index.html in an app folder, and /.settings.json — and GPIO is closed to guests until the owner allows it from the admin page. GET /apps is public and reports every app’s resolved rules, so an app can read its own before it tries; handle a 401 by telling the user rather than retrying. Every change to this contract moves the device’s API version (GET /version); what changed at each version lists them, with a migration prompt for updating an older app.

Writing an app

The fastest way in is to open one of the existing apps — every one on the apps page is a folder of a few readable files with no framework in them — and rewrite it into what you want. The minimal ones are deliberately small enough to read in a sitting. The app author’s guide is the full list of what a finished app does; the short form:

  • A folder: index.html, an app.json naming the API version and the verbs it needs, and pocket.js beside them. Everything the app needs lives in the folder; the device serves it as-is.
  • Relative URLs for its own files, and pocket.js for its reads and writes. On a refusal, put err.message where the person will see it.
  • Poll sparingly. It’s a microcontroller — a request every few seconds is fine, sixty a second is not.
  • For anything live, use the WebSocket rather than polling. Messages are broadcast to every other client as-is, so pick a small JSON shape and stick to it.
  • Expect the storage to be small and occasionally full, and expect clients to come and go as people wander in and out of Wi‑Fi range.

If you’d rather describe an app than write one, build with AI hands a model the same reference and gets a file back.

Moving an app up from v0

This section is for an app written against version 0 of this guide, which is firmware 0.3 and earlier. Firmware 0.4 introduced API version 1, and the change is a breaking one: an app is now a folder with a manifest, the device-wide guest switches are gone, and guests can no longer write at the top level of the card. An old app still runs, served read-only, until the steps below are done.

  1. Give the app a folder. Move its index.html into a folder of its own; the admin page offers to do this for a lone .html file. Keep its data files in the same folder.
  2. Add app.json beside it. Name the API version and only the verbs the app needs: {"api": 1, "title": "…", "paths": {"/": {"upload": "everyone"}}} is a guestbook’s whole manifest. The manifest has the grammar.
  3. Address its files relatively. fetch('board.json'), never fetch('/board.json'), and never a hard-coded folder name, so the folder can be renamed. Uploads go to POST /files?path=<its folder>, with the folder read from location.pathname. pocket.js does all of this for you, and swapping raw fetch calls for Pocket.readJson, Pocket.write and Pocket.list is the shortest path.
  4. Stop reading /auth/permissions. The endpoint is gone. An app that hides controls a guest cannot use reads its own entry in GET /apps, or calls Pocket.allows(verb).
  5. Explain a 401 in words. Send X-Requested-With on every request so the browser’s own password box stays closed, and put the reason where the person will see it. pocket.js does both; its rejections carry the sentence.
  6. If it uses the pins, ask for them. Add "gpio": true to the manifest. The pins stay closed to guests until the owner allows them from the app’s folder on the admin page, and the app should say so on a 401.
  7. If it read GET /home, read folder. The homepage is a folder now, and the answer is {"folder", "exists"}.

What changed at each API version is the full list, with the reserved folder names, and ends with a migration prompt you can hand to an AI assistant together with the app’s index.html. After an update, the admin page marks an app written for an older version when you open its folder and links there.