TL;DR — To run Node.js on Android as a service that stays up, embed Node with nodejs-mobile, start it inside a foreground service in its own process, and restart it from a boot receiver. Termux won’t do: a background terminal session is the first thing Android kills. Getting from a first working version to production took fixing a 62 MB
libnode.sothat wouldn’t load from inside the APK (useLegacyPackaging = true), a C++ runtime that wasn’t packaged (-DANDROID_STL=c++_shared), a Node build with no ICU, soAsia/Kolkatacrashed it (a fixed+05:30offset), a battery setting that stopped the service, and two log files with no size cap that would eventually take the diagnostics screen down with them.
The gap
Biometric terminals at a canteen counter need something on the local network that speaks their protocol and queues every scan safely through internet outages. The offline-queue post covers what that agent does. This one is about where it runs.
The agent is Node.js. On a Windows PC that’s easy. But many sites have no PC at the counter. What they have is an Android device that is already powered on, on the network and bolted down all day. Putting the agent there means one less box to buy, power and lose.
What I needed was a long-running Node process on Android: not an app someone opens, but a server that starts on boot and stays up for weeks. Nothing off the shelf does that out of the box. Termux runs Node, but as the project’s own design doc put it when I rejected it, “a background terminal session is first in line to be killed when Chrome wants memory.” nodejs-mobile embeds Node in an app, but keeping it alive is left to you.
The concepts this needs
Only three, and the rest is in the docs:
- Foreground service. An Android service that shows a persistent notification and, in
exchange, is among the last things the system kills. Since Android 14 it must declare a
type; an agent like this uses
specialUse. Android’s foreground-service docs cover the rules. - A separate process for Node. nodejs-mobile starts Node once per process and it can’t
be restarted inside it. Running the service in its own process (
android:process=":node") means a crash in Node takes down that process, not the UI, and the system can restart it. - A boot receiver. A
BroadcastReceiverforBOOT_COMPLETEDthat starts the service after a reboot, so a power cut at night doesn’t leave the counter dead in the morning.
The first working version
The same agent code ships to two targets. The differences are almost all about durability and survival:
| Windows PC | Android device | |
|---|---|---|
| Node | Node 22 as a single executable application, ~87 MB .exe | nodejs-mobile 18.20.4, embedded in the APK |
| Durable queue | SQLite, WAL mode, synchronous=FULL | Append-only log + snapshot file, fsync’d on every write, compacted every 20,000 entries |
| Stays up because | Scheduled task at startup | Foreground service in its own process |
| Starts after reboot | Scheduled task onstart, plus a firewall rule for the port | Boot receiver |
| Package size | ~87 MB | ~49 MB release APK (three CPU ABIs) |
Two shims made one codebase build for both. node:sqlite
only exists from Node 22.5, and nodejs-mobile is on Node 18, so the Android build swaps in the
file-backed store. The HTTP client is aliased to undici v6, the last major that runs on Node 18.
Why the queue must fsync before acknowledging a scan is covered in
the offline-queue post.
boot ──▶ BootReceiver ──▶ startForegroundService()
│
┌──────────────▼───────────────┐
│ AgentService (":node" proc) │ persistent notification
│ nodejs-mobile → agent.js │
│ listens on the LAN │◀── terminals push scans
│ append-log queue (fsync) │
└──────────────┬───────────────┘
│ HTTPS, one at a time
▼
backend
▼ the app's UI can be closed, swiped away or crash; the agent keeps running
Everything below happened between that first working version and a device that runs unattended at a counter.
What broke on the way to production
The 62 MB libnode.so wouldn’t load from the APK
Symptom. The app installed and the service started, but Node didn’t.
Cause. By default, modern Android builds leave native libraries uncompressed inside the APK
and map them directly from there, instead of extracting them at install. nodejs-mobile’s
libnode.so is 62,475,584 bytes, and on this setup it wouldn’t load that way.
Fix. packaging { jniLibs { useLegacyPackaging = true } } in the Gradle config, which
extracts native libraries to disk at install, as older Android versions always did
(the manifest equivalent is android:extractNativeLibs).
The cost is install size on disk. It’s worth it.
libc++_shared.so was never packaged
Symptom. With that fixed, Node still didn’t start: a native library it needs was missing.
Cause. libnode.so is built against the shared C++ runtime, libc++_shared.so. The app’s
own native code was built with the NDK’s default static runtime, so Gradle had no reason to
package the shared one, and nothing else on the device provides it.
Fix. Build the bridge with -DANDROID_STL=c++_shared in the CMake arguments. Gradle then
packages libc++_shared.so for each ABI. The
NDK’s C++ library guide explains why
one app shouldn’t mix the two.
Node without ICU can’t name a time zone
Symptom. Node started, then the service crash-looped.
Cause. The embedded Node build has no ICU, so it has no time-zone database. The agent
formatted times with the IANA name Asia/Kolkata, which fails without ICU. An uncaught error
at startup, inside a service the system restarts, is a crash loop.
Node’s internationalisation docs list what each ICU mode
supports.
Fix. Use a fixed +05:30 offset instead of the zone name. India has no daylight saving
time, so a fixed offset is exact here. It wouldn’t be for a site in a zone with DST.
These three hid behind each other
None of them was hard once seen. The problem was the order: Node can’t fail on a time zone until it loads, and it can’t load until its libraries are found, so each bug only showed up once the one before it was fixed, on a device with no console. What makes that bearable is on-device diagnostics: the service writes Node’s output to files the app can display and share. I’d build that first next time, before the feature.
A battery setting stopped the service
Symptom. On 14 October the agent on a test phone stopped and didn’t come back.
Cause. The phone’s battery setting for the app was “Restricted”. On many Android builds that lets the system stop even a foreground service.
Fix. Part of the install checklist now: set the app’s battery usage to “Unrestricted” and confirm the setting stays after a reboot. A foreground service is necessary for staying alive, and on some phones it still isn’t enough.
The diagnostics could crash the diagnostics
Symptom. None yet. An audit found it before a device did.
Cause. Two logs had no size cap. The app’s scan log was never rotated. The native stdout capture was only truncated when Node started, and under a foreground service Node runs for weeks. The “share diagnostics” button read the whole file into memory to show its last few kilobytes.
Fix.
- Rotate the app log at 5 MB into a single
.1file, so ~10 MB total, checking the size every 200 lines rather than on every write. - Cap the stdout capture at 1 MB and write a marker line where it was cut.
- Read only the tail, by seeking to the end, instead of reading the whole file.
Numbers, from a synthetic test on a laptop: the old read threw OutOfMemoryError on a
200 MB log with a 32 MB heap (-Xmx32m), and the tail read handled it. About 3.3 MB pushed
through the native logger stayed under the 1 MB cap. A burst of 3,000 scans held at 46 MB of
memory. My estimate of ~90 MB of log growth a year without the cap is an estimate. I didn’t
measure it.
The device’s address kept changing
Symptom. The terminal kept sending scans to an address the device no longer had.
Cause. The terminal is configured with the agent’s IP address. The device got its address from DHCP, and over the test period it was seen at three different addresses. Each change silently orphaned the terminal’s setting.
Fix. A DHCP reservation for the device on the site router. That’s the recommendation. I haven’t confirmed it’s in place at every site, so the checklist below asks for it explicitly.
Switching from a debug to a release build wipes the queue
Symptom. Lost scans, if it happens while the queue isn’t empty.
Cause. A debug-signed app can’t be upgraded in place to a release-signed one. Android requires uninstalling first, and uninstalling deletes the app’s data, including any scans still in the queue.
Fix. Install the release build from day one on anything that will ever hold real scans. If a debug build is already out there, drain its queue to empty before uninstalling.
Testing a new build without touching the live one
Not a break, but the fix for one kind: a second build flavor, “next”, with its own package name, data folder and task names. It installs beside the stable app on the same device and never shares its queue. A new build gets a real terminal without risking the agent that’s serving the counter.
A checklist you can copy
- Node runs inside a foreground service with a declared type, in its own process.
- A boot receiver starts it; tested with a real power cut, not just a reboot from settings.
-
useLegacyPackaging = true(orextractNativeLibs="true") if you ship a largelibnode.so. - Native code built with
-DANDROID_STL=c++_shared, andlibc++_shared.sopresent in every ABI. - No IANA zone names unless your Node build has ICU. Use fixed offsets, and only where there’s no DST.
- No
node:sqliteon Node 18; a durable store that fsyncs before acknowledging. - Dependencies pinned to versions that support the embedded Node’s major version.
- Battery usage “Unrestricted”, checked again after a reboot.
- Every log rotated or capped; diagnostics read the tail, never the whole file.
- On-device diagnostics working before the first field install.
- A DHCP reservation (or static IP) for the device the terminals point at.
- Release-signed from the first install that can hold real data.
- A side-by-side “next” flavor for testing on live hardware.
FAQ
Can you run Node.js on Android without root? Yes. nodejs-mobile embeds a Node build as a native library inside an ordinary APK, with no root and no Termux. Your app starts Node in a background thread and passes it a script. For a server that has to stay up, run it inside a foreground service in its own process.
Why not just use Termux? Termux is a terminal app. A process started from it is a background process with nothing telling Android it matters, so under memory pressure it’s among the first things killed. A foreground service tells the system the work is user-visible and ongoing, which puts it near the end of the kill order. For a service that has to survive weeks unattended, that difference decides everything.
Why does libnode.so fail to load on Android?
Usually one of two things. The library is left inside the APK and doesn’t load from there, which
useLegacyPackaging = true fixes by extracting it at install. Or its C++ runtime,
libc++_shared.so, isn’t packaged, which building with -DANDROID_STL=c++_shared fixes. Check
the second once the first is fixed. They show up one after the other.
How do I handle time zones in nodejs-mobile?
The embedded Node has no ICU, so IANA zone names like Asia/Kolkata throw. Use fixed UTC
offsets if your zone has no daylight saving time. Otherwise do zone conversion on the server, or
ship a small zone library with its own data instead of relying on Intl.
Does a foreground service guarantee Android won’t kill my app? No. It makes it far less likely, but battery-saving settings can still stop it on some devices. On one test phone, a “Restricted” battery setting stopped the service. Set the app to “Unrestricted”, check the setting survives a reboot, and have the service restart itself after a boot.
Is an Android device reliable enough to be a local server? For a light workload like queuing and forwarding scans, yes, if the queue is durable, the service survives reboots and memory pressure, logs are capped and the device has a fixed address. The hardware was never the weak point here. The defaults were: packaging, battery, logs and DHCP.
What I’d still improve
- Cap the Windows agent’s log too. The desktop build still has an uncapped log. Same fix, not yet shipped.
- Make the agent announce its address to the backend, so a changed IP shows up on a dashboard instead of as missing scans.
- A remote health check that alerts when a site’s agent goes quiet during service hours, instead of finding out from the counter.
- Move off Node 18 when nodejs-mobile ships a newer major. Node 18 is past end of life, and the shims exist only because of it.
I write about backend reliability, Postgres and edge systems from work on food-tech and healthcare platforms. More on what I build and how I work, on how the agent keeps scans safe through outages, and on why the backend answers every scan with a 200. If you’re about to put Node on a device you can’t reach, build the diagnostics screen first.