# nanovm: Runtime Environment https://nma.sh/llms.txt is the whole guide. ## Runtime Environment - Engine: QuickJS (upstream 2026-11-02): modern JavaScript, interpreted. - Snapshot execution: Top-level code runs once at build time. Variables, imported modules, and functions declared at top-level freeze into the microVM memory snapshot. Incoming HTTP requests execute the handler registered with serve(). - Handler: serve(req => { // req.method, req.path (with its query string: "/messages?n=20"), req.headers, req.body return "Hello world"; // or { status: 200, contentType: "text/html", headers: {...}, body: "..." } // two Set-Cookie: headers: [["set-cookie", a], ["set-cookie", b]] or Headers.append }); // a handler may return a Promise (setTimeout works) Content-Length is optional: the platform sends the body's byte length, and drops a different one (logged as "response dropped header: content-length"). HEAD: answer as for GET: the handler runs as HEAD first, and an app that answers HEAD keeps that answer; if that status is 404 or 405 the handler runs once more with a GET request (the same URL and headers, no body) and that answer's status and headers are sent, for no other method and no other status; the platform sends no body. serve and console are globals (no require() needed; require('serve') throws MODULE_NOT_FOUND). An app's top-level export default { fetch(request, env, ctx) } is the other form and registers its fetch handler: request is a Request (request.url, .method, .headers a Headers, .text(), .json(), .formData(), .arrayBuffer(), .body, .clone(); request.path stays readable), env.NAME is the secret (as secrets.get(NAME)), ctx.waitUntil runs before the answer, and ctx.passThroughOnException is a no-op; use one form, not both. Request properties: - req.method: string, uppercase HTTP method ("GET", "POST", etc.) - req.path: string, path with query string (e.g. "/items?k=v"); req.query is undefined (parse path if needed). Parse it with URLSearchParams: const query = new URLSearchParams(req.path.split('?')[1] || ''); query.get('k') - req.url: string, absolute ("https://HOST/items?k=v", http:// for a plain request); new URL(req.url) works, and a missing or malformed Host is localhost. - req.headers: object with lower-case header names and string values. Every request header reaches your app (Authorization, Content-Type, Accept, Origin, X-*) except hop-by-hop ones, and any X-Forwarded-*, Forwarded, X-Real-IP or X-NV-* the visitor sent. Repeated names are joined with ", ". host is the name the visitor used (its two words or N-TENANT, .nma.sh), and x-forwarded-proto and x-forwarded-host are set by the platform; on nma.sh x-real-ip and x-forwarded-for are the visitor's address, one value, set by the platform. Cookies reach you, except the platform's nv_tok and nv_dbt. The header block is at most 8 KiB; past it a 431. - req.body: string (always string, never Buffer or parsed). Empty body and GET give "". JSON remains unparsed string (use JSON.parse(req.body)). Non-UTF-8 bytes replace with \uFFFD. JSON bodies: let data; try { data = JSON.parse(req.body); } catch (e) { return { status: 400, body: "invalid JSON" }; } Form bodies (URLSearchParams is global): const form = new URLSearchParams(req.body); form.get('field') await req.formData() parses the same body by its content-type into a FormData: a urlencoded body, or multipart (a part with a filename is a File; req.body stays readable); a bad body, a missing multipart boundary or any other content-type rejects with TypeError. - crypto.getRandomValues(typedArray) (up to 65536 bytes) and crypto.randomUUID() are globals, from the hardware's randomness. require('crypto') has createHash, createHmac, randomBytes, randomFillSync, randomInt, randomUUID, getRandomValues, subtle, webcrypto, timingSafeEqual, pbkdf2 and pbkdf2Sync (digest sha1, sha256, sha384, sha512), but no scrypt: derive keys with one of those, or crypto.subtle.deriveBits({name: "PBKDF2", hash: "SHA-256", salt, iterations}, key, bits). - Frozen values: top-level code runs once, before the snapshot. Math.random(), crypto.randomUUID(), crypto.getRandomValues() and Date.now() taken at top level are the same in every VM of a version; take them inside the handler. - Logs: console.log and friends go to the app's logs. - Node.js compatibility: require() (with or without 'node:') has: path, events, util, querystring, url, assert, buffer, crypto, stream, stream/promises, string_decoder, timers, timers/promises, os, util/types, assert/strict, path/posix, path/win32, punycode, async_hooks, diagnostics_channel, perf_hooks, module, http, https, worker_threads, inspector and vm. http and https have IncomingMessage, Agent, STATUS_CODES and METHODS; their servers and requests, a Worker, a debugger and another realm throw ERR_NOT_AVAILABLE. Not fs, net or child_process: serve() is the server, and there is no file system. Anything else throws MODULE_NOT_FOUND when the app is built. One file, no npm install: bundle dependencies into app.js. - Data Plane APIs: kv, db, crdt and secrets are globals on globalThis (no require() needed; require('kv') throws MODULE_NOT_FOUND). - kv: Fast key-value store, cached at the edge. kv.delete(key) -> true if it held a value, else false; kv.list as db.list without reverse (eventual). kv.get(key, [{consistency: "session"|"eventual"}]) -> string | null kv.put(key, value) -> v (the key's new version, a number) kv.token() -> string (causal consistency token) - db: Sharded transactional store with compare-and-swap. db.get(key, [{consistency: "session"|"eventual"|"strong"}]) -> string | null db.put(key, value) -> v (the key's new version, a number) db.getv(key) -> {value: string, v: number} | null. db.token() -> string db.cas(key, expected_v, new_value) -> the new v, or null if the key moved on (read again and retry) db.cas(key, 0, value) creates a key that does not exist yet, or was deleted (null if it holds a value) db.delete(key) -> true if it held a value (now it reads null), else false. db.cas(key, v, undefined) -> true or null db.list(prefix, [{limit: 1..1000 (100), after, reverse}]) -> {keys, next}: key order, strong; reverse: true is descending and after means below it; next (or null) is the next after. The second argument is one object as shown, never an array (kv.get, db.get and db.getv take theirs the same way): db.list("msg:", { limit: 50, after: next }) - crdt: conflict-free counters and registers. const c = crdt.counter(name); c.add(1); c.value() -> number const r = crdt.register(name); r.set(val); r.get() -> string Data belongs to the tenant, not the app: every app of one account sees the same kv, db and crdt names, so an admin app reads what an orders app wrote. Keep apps apart with a prefix ("orders:"). Prefix names with the app's ("notes:42", not "42"). Values are strings: put(key, null) stores "null". db.put, db.cas and kv.put stringify any value as String(v) does: JSON.stringify an object or number yourself. Data survives a redeploy, a rollback, a VM's restart and the app's delete. There is no restart command: any request may land in a VM newly restored from the snapshot, so keep state in kv, db or crdt, never in top-level variables. - Network: await fetch(url, init) -> Response (text(), json(), arrayBuffer()), made by the host: https:// on 443 only. Apps on nma.sh, yours or anyone's (https://WORD-WORD.nma.sh/, https://N-TENANT.nma.sh/), answer as a browser sees them (no X-Real-IP), in the same rate; a chain of apps fetching apps stops after 4 with "fetch refused: loop". Every other host must be public (private, loopback, link-local, CGNAT, metadata 169.254.169.254 and the host's own are refused, at every redirect too, 5 at most); a refusal is TypeError "fetch refused: ". No raw TCP/UDP. - Secrets: secrets.get(NAME) reads this app's own secret, set with 'secret set'; no other app or tenant sees it. Call it inside the handler (see "secret set" above for the pattern).