Docs

Device screens: your device's own page in the Connectivitizer app

Your device can bring its own screen: one HTML page that it serves itself. The Connectivitizer app shows that page when someone taps the device, and cz ui shows it in a browser on a computer.

You don't build or publish an app, and nothing is uploaded anywhere. The page reaches the screen over the same end-to-end encrypted session as everything else, and when you change it on the device, the next open shows the new version.

Desk lampPeer to peer · end-to-end encrypted
The page from this guide · Simulated data
greenhousePeer to peer · end-to-end encrypted
Greenhouse · Simulated data

This guide takes a device that already connects (the quickstart at https://connectivitizer.com gets you there) and gives it the page on the left in a few minutes: a switch, a slider and a value the device reports. Then it shows how to try changes on your computer, how to add your own controls, colours, the camera and the other things a page can do, and finished examples to start from. You have never written a web page? Section 1 explains the little you need.

How it works

Your deviceAn ordinary web server on the device, exposed as the service "api" (or "ui").
  • GET /.cz/ui.jsonthe manifest: name, entry, colours
  • GET /.cz/ui.htmlthe page: one HTML file
  • GET /state · POST /togglewhatever your page asks for
Connectivitizer appAsks for the manifest and the page, and shows the page below its own bar.‹ Desk lampyour page
The page comes from the device every time it is opened. Nothing is uploaded, and Connectivitizer never sees it.

When the app opens the device, it connects to the service named ui, else api, else the device's only service. Then it asks for two files with GET:

The app asks forThe device answers
/.cz/ui.jsonthe manifest, application/json: {"name": "Desk lamp", "entry": "/.cz/ui.html", "version": "1"}
/.cz/ui.htmlthe page, text/html: one file with its scripts and styles inline, at most 2 MB, served uncompressed

A device without a screen answers /.cz/ui.json with 404. Everything else the page asks for (fetch("/state")) goes to the same service, so your device's web server is all there is to it.

1. The page

Save this as ui.html. It shows whether the lamp is on, a button switches it, a slider sets its brightness, and it shows how long the device has been running, refreshed every two seconds:

HTML
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">


<style>
  body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
  h1 { font-size: 44px; margin: 4px 0 24px; }
  label { display: block; margin: 28px 0 8px; }
  button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
  input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
  input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>


<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>

<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">

<p>Running for <b id="uptime">…</b> s</p>


<script>
  const $ = (id) => document.getElementById(id);

  // The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
  // show() puts it on the page: one line per value.
  const show = async (response) => {
    const s = await response.json();
    $('state').textContent = s.on ? 'On' : 'Off';
    $('level-value').textContent = s.level;
    if (document.activeElement !== $('level')) $('level').value = s.level;
    $('uptime').textContent = s.uptime;
  };
  const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });

  // A tap or a change sends a request; the answer is shown right away.
  $('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
  $('level').oninput = () => { $('level-value').textContent = $('level').value; };
  $('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);

  refresh();
  setInterval(refresh, 2000);   // new values every 2 seconds
</script>
</html>

fetch('/state') goes to the device, through the app. The same page also works when you open it in a browser straight from the device on your own network.

New to HTML, CSS and JavaScript?

You don't need to learn much of them for a page like this. The page has three parts, each marked in the code above:

  • HTML is what is on the page: a heading, a button, a slider. Each element that the script changes or listens to has an id, such as id="toggle".
  • CSS (in <style>) is how it looks: sizes, colours, spacing. Change a colour code like #b58900 and the button changes.
  • JavaScript (in <script>) is what happens. $('toggle') finds the element with id="toggle"; .onclick = … says what a tap does.

A tap travels like this: the button's onclick calls fetch('/toggle', { method: 'POST' }), the request goes through the app to your device, the device runs its /toggle route and answers with its state as JSON ({"on":true,"level":40,"uptime":120}), and show() writes each value into the page. Every control in this guide works the same way, so adding one means three small steps: an element in the HTML, a line in the script that sends its request, and a route on the device that answers it.

To see errors, open the page in the preview (section 4) and press F12 (on a Mac, Cmd+Option+I): the Console shows every error with its line. Section 5 has ready-made controls to copy.

Let an AI assistant write it. Assistants are good at exactly this. Give yours the page and your device's code, and a request like:

Add a control to my Connectivitizer device screen (ui.html) and the matching route to my device's web server. The control: a number field "Target temperature", 5 to 35 in steps of 0.5, sent as POST /target?value=<number>; the device keeps it and adds "target" to the JSON it answers /state with. Keep the page one file with inline CSS and JavaScript, no external files, no localStorage or cookies, and use fetch with paths like /target, never the device's address. The rules are in https://connectivitizer.com/guides/device-screen.md.

2. Serve it

Pick the language of your device. Each snippet is a complete web server on 127.0.0.1:8080, the address the device guides expose as the service api, and it answers the two files plus the page's own requests: GET /state, POST /toggle and POST /level?value=40, each answered with the state. On an ESP32 the routes go on the sketch's own web server instead.

C++
// In the sketch: the routes go on the WebServer that is exposed as "api" (port 80).
static const char UI_JSON[] PROGMEM = R"({"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"})";
static const char UI_HTML[] PROGMEM = R"html(<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">


<style>
  body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
  h1 { font-size: 44px; margin: 4px 0 24px; }
  label { display: block; margin: 28px 0 8px; }
  button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
  input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
  input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>


<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>

<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">

<p>Running for <b id="uptime">…</b> s</p>


<script>
  const $ = (id) => document.getElementById(id);

  // The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
  // show() puts it on the page: one line per value.
  const show = async (response) => {
    const s = await response.json();
    $('state').textContent = s.on ? 'On' : 'Off';
    $('level-value').textContent = s.level;
    if (document.activeElement !== $('level')) $('level').value = s.level;
    $('uptime').textContent = s.uptime;
  };
  const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });

  // A tap or a change sends a request; the answer is shown right away.
  $('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
  $('level').oninput = () => { $('level-value').textContent = $('level').value; };
  $('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);

  refresh();
  setInterval(refresh, 2000);   // new values every 2 seconds
</script>
</html>)html";
static bool on = false;
static int level = 50;

static void sendState() {
  String json = String("{\"on\":") + (on ? "true" : "false") + ",\"level\":" + level +
                ",\"uptime\":" + (millis() / 1000) + "}";
  server.send(200, "application/json", json);
}

// in setup(), before server.begin():
server.on("/.cz/ui.json", HTTP_GET, [] { server.send_P(200, "application/json", UI_JSON); });
server.on("/.cz/ui.html", HTTP_GET, [] { server.send_P(200, "text/html; charset=utf-8", UI_HTML); });
server.on("/state", HTTP_GET, sendState);
server.on("/toggle", HTTP_POST, [] {
  on = !on;   // switch your pin here: digitalWrite(LED_PIN, on);
  sendState();
});
server.on("/level", HTTP_POST, [] {
  level = constrain(server.arg("value").toInt(), 0, 100);   // e.g. analogWrite(LED_PIN, level * 255 / 100);
  sendState();
});

3. Open it

The device list in the app
The device list in the app
A device's screen in the app
A device's screen in the app
  • On the phone: in the Connectivitizer app, tap the device. The first time, add the device's shared key under Account › Keys › Add a key: The Connectivitizer app explains how.
  • On the computer: cz ui <device> opens the page in your browser, through Connectivitizer, with the keys staying on your machine (cz). The web app at https://connectivitizer.com does not show device screens, because your shared key would have to be used on our website.

To change the page, edit it, then restart the device's program (or flash the ESP32 again) and open the device again. The app always loads the page the device serves now. While you are still trying things, the preview below is quicker.

If devices are limited to certain clients (Clients allowed to connect on the device's page in the web app), the app is the client Connectivitizer.

4. Try changes on your computer

screen-preview.mjs shows your ui.html in the browser on your computer and reloads it each time you save. It is one file for Node.js 18 or later, with nothing to install:

Bash
curl -fsSLO https://connectivitizer.com/downloads/tools/screen-preview.mjs
node screen-preview.mjs ui.html --fake fake-device.js --open

Without the device: --fake answers the page's requests with a pretend device, so you can work on the page before the device's code exists, or away from the hardware. This one answers the starter page; save it as fake-device.js and give it a route for each request your page makes:

JavaScript
// fake-device.js: answers the page's requests the way the device will, with made-up values.
czDemo.define({
  routes: {
    'GET /state': (request, ctx) => state(ctx),
    'POST /toggle': (request, ctx) => {
      ctx.state.on = !ctx.state.on;
      return state(ctx);
    },
    'POST /level': (request, ctx) => {
      ctx.state.level = Math.min(100, Math.max(0, Number(request.query.get('value')) || 0));
      return state(ctx);
    },
  },
});

function state(ctx) {
  return { on: ctx.state.on === true, level: ctx.state.level ?? 50, uptime: Math.round(ctx.seconds()) };
}

request.query.get('value') is what the page sent after ?value=, ctx.state keeps values between requests, and ctx.seconds() counts from the start. What a route returns is the answer, as JSON.

With the device: --device sends the page's requests to the real device, while the page comes from your file. On an ESP32 nothing has to be flashed until the page is done:

Bash
node screen-preview.mjs ui.html --device http://192.168.1.50      # the ESP32 on your network (WiFi.localIP())
node screen-preview.mjs ui.html --device http://127.0.0.1:8080    # a program on this computer

The preview runs the page under the same rules as the app (its Content-Security-Policy), so what works here works there. It also prints what the app would refuse, such as a picture loaded from the device by its address or the use of localStorage. When the page is done, put it on the device: replace ui.html next to the program and restart it, or on an ESP32 paste it into the UI_HTML string and flash.

5. Add controls

Each control below adds to the starter page: the HTML goes with the other elements, the script lines into <script>, and the show() line into show(). Every control sends its value after ?value=, so the device reads them all the same way, and every route answers with the state, so the page shows the result at once. Add the new values to the JSON your device answers /state with.

A button that does something once, POST /feed:

HTML
<button id="feed">Feed the fish</button>
JavaScript
$('feed').onclick = () => fetch('/feed', { method: 'POST' }).then(show);

An on/off switch, POST /pump?value=1 or ?value=0, and "pump": true in the state:

HTML
<label><input id="pump" type="checkbox"> Pump</label>
JavaScript
$('pump').onchange = () => fetch('/pump?value=' + ($('pump').checked ? 1 : 0), { method: 'POST' }).then(show);
// in show():
$('pump').checked = s.pump;

A number field with a button, POST /target?value=21.5:

HTML
<label for="target">Target temperature (°C)</label>
<input id="target" type="number" min="5" max="35" step="0.5"> <button id="save">Save</button>
JavaScript
$('save').onclick = () => fetch('/target?value=' + $('target').value, { method: 'POST' }).then(show);
// in show(), so that typing is not overwritten:
if (document.activeElement !== $('target')) $('target').value = s.target;

A slider is in the starter page: <input type="range"> with oninput for the number next to it and onchange to send it when the finger lifts.

A text field, POST /name?value=…:

HTML
<label for="name">Name on the display</label>
<input id="name" maxlength="40"> <button id="rename">Save</button>
JavaScript
$('rename').onclick = () => fetch('/name?value=' + encodeURIComponent($('name').value), { method: 'POST' }).then(show);

encodeURIComponent lets spaces and other characters through; the device's web server decodes them.

A choice from a list, POST /mode?value=auto:

HTML
<label for="mode">Mode</label>
<select id="mode">
  <option value="auto">Automatic</option>
  <option value="on">Always on</option>
  <option value="off">Off</option>
</select>
JavaScript
$('mode').onchange = () => fetch('/mode?value=' + $('mode').value, { method: 'POST' }).then(show);
// in show():
$('mode').value = s.mode;

A value the device reports, "temperature": 21.4 in the state, refreshed with everything else:

HTML
<p>Temperature: <b id="temperature">…</b> °C</p>
JavaScript
// in show():
$('temperature').textContent = s.temperature.toFixed(1);

A warning that shows only when needed, "tankEmpty": true in the state:

HTML
<p id="tank-warning" hidden style="color: #b00020"><b>The tank is empty.</b></p>
JavaScript
// in show():
$('tank-warning').hidden = !s.tankEmpty;

A small chart of the last values, drawn as a line in SVG:

HTML
<svg viewBox="0 0 290 80" width="100%" height="80"><polyline id="line" fill="none" stroke="currentColor" stroke-width="2" /></svg>
JavaScript
const recent = [];
// in show():
recent.push(s.temperature);
if (recent.length > 30) recent.shift();
const low = Math.min(...recent), high = Math.max(...recent), span = high - low || 1;
$('line').setAttribute('points', recent.map((v, i) => i * 10 + ',' + (75 - ((v - low) / span) * 70)).join(' '));

On the device, each control is one more route next to /level in the starter server of your language, and the value is read the same way everywhere:

DeviceThe value after ?value=
ESP32 (Arduino)server.arg("value"), with .toInt() or .toFloat() for a number
Node.jsurl.searchParams.get('value')
Pythonparse_qs(url.query).get("value", [""])[0]
C# / .NETa parameter of the handler: (int value), (double value) or (string value)
Java, Kotlinexchange.getRequestURI().getQuery() is value=…; for text, decode it with URLDecoder.decode(…, StandardCharsets.UTF_8)

On an ESP32, the switch above is:

C++
static bool pump = false;
// in setup():
server.on("/pump", HTTP_POST, [] {
  pump = server.arg("value") == "1";
  digitalWrite(PUMP_PIN, pump);
  sendState();   // with ",\"pump\":" + String(pump ? "true" : "false") added to its JSON
});

6. Talk to the device

  • fetch("/info") and fetch("/led", { method: "POST", body: "on" }) go to the device, through the app.
  • window.connectivitizer.webSocket("/events") opens a WebSocket to the device. A browser new WebSocket(...) does not reach it.
  • Files on the device are not loaded by URL: <img src="/snapshot.jpg"> stays empty. Fetch them instead: URL.createObjectURL(await (await fetch("/snapshot.jpg")).blob()) gives a blob: URL for an <img>.
  • window.connectivitizer exists only in the app (and in cz ui), so check for it, and the page also works when opened straight from the device.

7. Give it colours

Desk lampPeer to peer · end-to-end encrypted
The page from this guide · Simulated data
Desk lampPeer to peer · end-to-end encrypted
The same page with a theme in ui.json · Simulated data

The app's bar above the page (the device's name, the connection line and the phone's status bar) can take the page's colours. Add a theme to ui.json:

JSON
{ "name": "Desk lamp", "entry": "/.cz/ui.html", "version": "2",
  "theme": { "background": "#fdf6e3", "foreground": "#3b3526" } }

Give the page's <body> the same background, so nothing flashes while it loads. A page that changes its look (day and night) calls window.connectivitizer?.setTheme({ background, foreground }), and setTheme(null) goes back to the manifest's. Colours are #rgb or #rrggbb, and the two have to be readable together (a contrast of at least 4.5 : 1); otherwise the app keeps its own. The bar's text and buttons stay the app's.

A theme for the whole app: ui.json can also offer up to three themes for the whole app, "appThemes": [{ "id": "camera-green", "name": "Camera green", "version": "1", "palette": { … } }]. The palette has every colour of the app's own themes as #rgb or #rrggbb: background, card, text, muted, border, tint, onTint, good, goodBackground, warn, warnBackground, bad, badBackground, neutralBackground. The app asks once whether to add a theme, and again only when its colours or version change; added themes are chosen under Account › Appearance and stay on the phone. A theme that makes text or warnings hard to read is refused: text needs a contrast of 4.5 : 1 on its backgrounds, as do onTint on tint and good, warn and bad on their own backgrounds; muted and tint need 3 : 1 on background and card, bad and warn 3 : 1 on card, and border 1.2 : 1 on card.

8. What a page can and cannot do

The app shows the page under a Content-Security-Policy that the page cannot loosen:

  • Your device, and the internet over https:. Inline scripts and styles run. Scripts, styles, pictures, video, fonts and frames load from https: addresses (your own server, map tiles, a library from a CDN), and fetch("https://…"), XMLHttpRequest and new WebSocket("wss://…") reach https: and wss: servers. Plain http: is blocked, and so are forms and eval.
  • Links, camera, microphone and location only if the person allows them. Each person who uses the app decides for themselves, under Account › Security: Device pages may open links, … may ask for the camera, … may ask for the microphone, … may ask for your location. All four are off at first. While one is off, your page's request is refused without a question (getUserMedia() rejects with NotAllowedError, a location request fails with PERMISSION_DENIED, a link does nothing), and the app tells the person, each time, that they can turn it on. While it is on, the app asks, with your device's name and what the page wants ("Greenhouse wants to use the camera", or the full address of a link): Allow once counts for that one request, Always allow for every later request of your device's page for the same thing (for a link, that exact address). The person can forget such decisions under Account › Security. A link is asked about only right after a tap on the page, at most three times a minute; a page that navigates by itself gets nowhere. Places in the page (#/settings) work.
  • Photos and files when the person picks them, whatever the switches say: <input type="file" accept="image/*" capture="environment"> opens the phone's camera or file picker on a tap, and the page can send the picture to its device (fetch("/upload", { method: "POST", body: file })).
  • No stored data: no localStorage, no cookies. What has to last belongs on the device.

Asking the person to turn something on. Expect the refusal and say what to do, next to the button that needs it:

JavaScript
async function startScanner() {
  try {
    video.srcObject = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
  } catch (error) {
    hint.textContent = window.connectivitizer
      ? "To scan, turn on \"Device pages may ask for the camera\" under Account › Security in the Connectivitizer app, then tap Scan again."
      : "The camera is not available.";
  }
}
scanButton.onclick = startScanner;

Ask from a button rather than when the page opens: the person then knows why the question comes. Each tap asks again, so ask once per action, not in a loop. Whatever the camera, microphone or location gives your page goes where your page sends it: to your device, or to a server you name. Connectivitizer does not receive it.

On an ESP32, embed the page in the firmware (ESP-IDF EMBED_TXTFILES, Arduino a PROGMEM string as above) and keep it small, tens of KB.

9. Examples to start from

Each archive has a finished page, the code for its device (or devices), and a README. They run on the start page of https://connectivitizer.com with simulated data; demo-kit/ in each archive is what simulates the device, so a page can be tried and changed without the hardware. Code opens the same files in the browser, to read before downloading.

ExampleDeviceLookCodeDownload
Greenhouse: soil, climate, tank, a pumpESP32, Arduino sketchsoft, botanicalCodehttps://connectivitizer.com/downloads/examples/greenhouse.zip
LED strip: colour, brightness, effectsESP32, Arduino sketchneon glassCodehttps://connectivitizer.com/downloads/examples/lights.zip
Rover: a joystick over a WebSocket, with a dead-man stopESP32, Arduino sketchretro arcadeCodehttps://connectivitizer.com/downloads/examples/rover.zip
Aquarium: a lamp that follows the day, a feeder, the water's temperatureESP32, Arduino sketchliving sceneCodehttps://connectivitizer.com/downloads/examples/aquarium.zip
3D printer companion, with a simulated printerRaspberry Pi, PythonblueprintCodehttps://connectivitizer.com/downloads/examples/printer.zip
Observatory: a simulated telescope, and a PC at home that stacks its framesRaspberry Pi and a PC, Pythonnight visionCodehttps://connectivitizer.com/downloads/examples/observatory.zip
Home lab: load and containers of a serverLinux PC or Raspberry Pi, Python, exposed with czclean rackCodehttps://connectivitizer.com/downloads/examples/homelab.zip
PC stats: CPU, memory, GPU, disks, networkWindows PC, C#terminal greenCodehttps://connectivitizer.com/downloads/examples/pc-stats.zip
Two lamps in two homes: touch one, the other glowstwo Raspberry Pis, Pythonwarm eveningCodehttps://connectivitizer.com/downloads/examples/lamps.zip
Two lamps, two homes, one connectiontwo ESP32s, Arduino sketchrings of lightCodehttps://connectivitizer.com/downloads/examples/lamps-esp32.zip
Arcade duel: two cabinets in two homes, one matchtwo Raspberry Pis, Pythonglowing vectorsCodehttps://connectivitizer.com/downloads/examples/arcade.zip
Mailbox: a sensor at the mailbox calls a light indoorstwo ESP32s, Arduino sketchespaper and postmarkCodehttps://connectivitizer.com/downloads/examples/mailbox.zip
Sightings (field log): a journal of birds and butterflies with a photo, species, count, a voice note and the location, sent to the deviceany PC or a container, Node.jsnature journalCodehttps://connectivitizer.com/downloads/examples/field-log.zip

In the observatory and the last four, more than the phone opens sessions to the device: a program on a PC, or a second device; their READMEs show how. Each README says what of it has been run and on what. The sketches compile; unless a README says otherwise they have not been run on hardware.

When something does not work

The app says
"This device brings no screen of its own"The device answers /.cz/ui.json with 404 or with something that is not JSON. curl http://<device>/.cz/ui.json on its network shows what it answers. Check that the web server with the two routes is the one exposed as ui or api.
The screen stays emptyThe page fails in the WebView. Open it in a browser from the device (http://<device>/.cz/ui.html) and check its console. A picture, script or font from a URL, also <img src="/…"> on the device, is blocked in the app: inline it, or fetch it and show it from a blob: URL.
The page shows, but buttons do nothingThe page's own requests (/state, /toggle here) go to the same service: check that the server answers them, and that they are paths (/state), not addresses (http://192.168.…/state).
A control does nothing, and the console says Cannot set properties of nullAn id in the script that is not in the HTML, or spelled differently: $('toggle') needs id="toggle".
The console says Unexpected token or is not valid JSONThe device's answer is not JSON. Open http://<device>/state in a browser on its network and look at it; on an ESP32 a missing \" in the string that builds the JSON is the usual cause.
The device answers 404 or 405 to a controlThe path or the method differs: fetch('/pump', { method: 'POST' }) needs a route for /pump that takes POST (HTTP_POST on the ESP32).
A value arrives as 0 or emptyThe name after ? differs between the page and the device: ?value= in the page, server.arg("value") (or your language's way, section 5) on the device.
It works in the preview, not on the deviceThe device still serves the old page: restart its program or flash the ESP32 again, then open the device again in the app.
Keys, access and connection messagesThe Connectivitizer app, "When something does not work".