NioJS v0.3.0
Release v0.3.0 Small Runtime Footprint Rust + QuickJS + PyO3 + Zig + Go + C

The Hybrid, Agent-Native Worker Runtime

Write simple TypeScript/JavaScript handlers. Import dependencies directly by URL. Offload compute to native Rust, dynamically bind Zig and Raw C via FFI, integrate Go cloud APIs, and run in-process Python AI. Package your verified application into a single immutable .njs capsule.

1. Mental Model & Architecture

Traditional runtimes (Node.js, Deno, Bun) are designed for heavy server runtimes with deep dependency graphs, long startup times, and hundreds of megabytes of node_modules.

NioJS reimagines workers for the AI agent era:

  • Engine Core: Embedded QuickJS-NG (rquickjs 0.14) inside an asynchronous multi-threaded Tokio / Hyper Rust host.
  • Compact Runtime: Embedded JavaScript execution and HTTP serving in a Rust host.
  • Hybrid Compute Offloading: JavaScript handles routing and JSON orchestration. Heavy computation escapes seamlessly to native Rust machine code (/** @native */), dynamically compiled Zig & Raw C FFI, Go cloud APIs, or in-process Python AI algorithms.
  • Zero node_modules: Modules are imported by HTTPS URL (esm.sh / UNPKG) with cryptographic SHA-256 lockfile pinning.
  • Single-File Capsules: Ship prepared application bytecode, dependency edges, and assets in one .njs artifact, with optional publisher signing. Read the complete capsule guide.
┌────────────────────────────────────────────────────────────────────────┐
│                          NioJS Host (Rust)                            │
│                                                                        │
│  ┌───────────────────────┐          ┌───────────────────────────────┐  │
│  │    Tokio HTTP Core    │          │   Multi-Worker Thread Pool    │  │
│  │ (Reusable Port Socket)│          │   (Pinned per CPU Core)       │  │
│  └───────────┬───────────┘          └───────────────┬───────────────┘  │
│              │                                      │                  │
│              ▼                                      ▼                  │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                       QuickJS Runtime                            │  │
│  │   • Ultra-fast routing ('nio.js')                                │  │
│  │   • Direct string & zero-alloc JSON serialization                │  │
│  └───────────┬──────────────────────────────────────┬───────────────┘  │
│              │                                      │                  │
│              ▼                                      ▼                  │
│  ┌────────────────────────┐              ┌──────────────────────────┐  │
│  │   /** @native */       │              │    In-Process Python     │  │
│  │   Rust Offloading      │              │  (PyO3 CPython Engine)   │  │
│  └────────────────────────┘              └──────────────────────────┘  │
└────────────────────────────────────────────────────────────────────────┘

2. Installation & Quickstart

Automated One-Line Install

For macOS, Linux, and Android (Termux):

curl -fsSL https://raw.githubusercontent.com/nio-labs/nio-js/main/install.sh | bash

For Windows (PowerShell):

irm https://raw.githubusercontent.com/nio-labs/nio-js/main/install.ps1 | iex

Using the NPM Launcher

# Run without installing:
npx @nio-labs/nio-js --help

# Or install globally:
npm install -g @nio-labs/nio-js

Building from Source

git clone https://github.com/nio-labs/nio-js.git
cd nio-js
cargo build --release
sudo install -m 755 target/release/nio-js /usr/local/bin/nio-js

3. CLI Command Reference

Command Arguments / Options Purpose
nio-js init [kind] --name <n>, --framework <fw> Interactive scaffolder for web/mobile apps and backend services.
nio-js run <entry> --port <p>, --host <h>, --workers <n> Launch a live dev server from a .ts, .js, or .njs file.
nio-js build <entry> -o <out.njs>, --update, --frozen, --offline Resolve, download, and bundle all dependencies into an immutable capsule.
nio-js check <entry> --format=agent-json, --format=pretty Perform instant syntax and module dependency validation without listening.
nio-js task <name> None Run native orchestration scripts defined in nio.toml.
nio-js mcp None (stdio transport) Run standard Model Context Protocol server for Claude, Cursor, and Nio.
nio-js inspect <capsule> Path to .njs file Display capsule graph topology, SHA-256 digests, and embedded assets.
nio-js verify <capsule> Path to .njs file Cryptographically verify all digest checksums and graph integrity.

4. Project Scaffolding (Add-on)

You can optionally scaffold a new full-stack project or mobile app using the interactive initialization tool:

nio-js init

This auto-generates a wired frontend (Vue, React, Svelte, etc.) and a NioJS backend with native tasks, or a backend-only server. You can run it interactively, or pass flags to skip prompts:

Option Description
-n, --name <NAME> The project directory name.
-f, --framework <FW> The frontend framework (e.g., React, Vue, Svelte, Lit, Vanilla, Blank).
-d, --db <DB> Database selection (e.g., nio-db or None).
-a, --ai <AI> AI integration (e.g., NioAI or None).

Example one-liner for a full React web app:

nio-js init web --name my-app --framework React --db nio-db --ai NioAI

Example for a backend-only server project:

nio-js init server --name my-api --db nio-db --ai None

Benchmarks

Compute & Throughput Microbenchmarks

Workload NioJS ops/s NioJS (@native) NioJS (Rust) NioJS (Zig) Node ops/s Bun ops/s Deno ops/s Verdict
HTTP GET throughput 7,497,1515,786,23431,762,165281,531,750 12,553,0379,394,43514,963,340🏆 NioJS (Zig)
JSON.parse small payload 469,744386,8433,875,988,4493,759,389,614 846,643993,7851,124,574🏆 NioJS (Rust)
JSON.parse large payload 9971,018151,512,929138,887,831 3,2924,8884,205🏆 NioJS (Rust)
JSON.stringify small object 200,917166,3303,703,681,8903,184,741,078 1,090,2221,284,9342,027,624🏆 NioJS (Rust)
JSON.stringify medium object 20,06517,2101,515,172,0491,265,816,877 174,789249,603222,776🏆 NioJS (Rust)
SHA 256 hashing small buffer 177,540144,0421,136,354,9841,315,795,579 734,751970,007602,176🏆 NioJS (Zig)
SHA 256 hashing large buffer 2,7322,273855,286693,818 126,651238,37953,539🏆 NioJS (Rust)
Buffer copy 64 KB 371,644295,875360,558118,764,664 37,48880,32431,209🏆 NioJS (Zig)
Array map plus reduce 801713170,53384,950 7,30026,2646,456🏆 NioJS (Rust)
String concatenation 6,9256,12214,797,276377,355,286 117,694258,178119,292🏆 NioJS (Zig)
Integer loop plus arithmetic 1,0767,1972,404,3092,197,850 24,12621,41322,267🏆 NioJS (Rust)
Integer loop with randomized input 1,2711,3022,595,4482,279,046 23,71221,72421,837🏆 NioJS (Rust)

Benchmark Highlights (Bare Metal HTTP)

Measured using 1-round "quick" methodology without warmup:

Criterion NioJS (Base) NioJS (@native) NioJS (Rust) Bun Node Deno Verdict
Startup7.3 ms7.3 ms14.5 ms12.2 ms55.2 ms18.8 ms🏆 Clear Win (NioJS Base)
Idle RSS11.6 MiB11.6 MiB13.8 MiB13.3 MiB46.8 MiB34.6 MiB🏆 Clear Win (NioJS Base)
/constant73,279 req/s73,279 req/s73,279 req/s71,899 req/s59,560 req/s66,294 req/s🏆 Clear Win
/callback74,105 req/s74,105 req/s74,105 req/s72,939 req/s63,430 req/s70,231 req/s🏆 Clear Win
/json71,280 req/s71,280 req/s73,150 req/s68,428 req/s50,888 req/s61,915 req/s🏆 Clear Win (Rust parsing)
/cpu (100k loop)4,215 req/s70,988 req/s73,250 req/s9,239 req/s8,863 req/s9,164 req/s🚀 Crushing Win (Rust/Native)

With this, NioJS looks unbeatable for anyone seeking peak performance without leaving the JS ecosystem.

5. Route Registration

Services import methods directly from 'nio.js'. Supported verbs include get, post, put, del, patch, head, and options:

import { get, post, del } from 'nio.js';

// 1. Zero-JS constant route: evaluated once, served instantly from Rust host
get('/', 'Hello from NioJS!');

// 2. Synchronous handler
get('/health', () => ({ status: 'ok', uptime: 104 }));

// 3. Asynchronous handler
get('/stats', async () => {
  const dbData = await fetchExternalData();
  return { data: dbData };
});
Registration Lifecycle: Routes must be registered during the evaluation of the entry file. Once the server binds to its port, registration closes permanently to prevent dynamic race conditions.

6. Requests, Responses & Status Codes

Handlers can return primitive values, plain JSON objects, binary buffers, or explicitly formatted responses via reply():

import { post, reply } from 'nio.js';

post('/api/orders', async ({ json }) => {
  const order = await json();
  if (!order.item) {
    return reply(
      { error: 'Field "item" is required' },
      { status: 400, headers: { 'x-service-error': 'VALIDATION_ERR' } }
    );
  }

  return reply({ orderId: 'ord_99', status: 'created' }, { status: 201 });
});

Response Type Coercion Table

Return Value HTTP Status Content-Type Internal Pipeline
string 200 OK text/plain; charset=utf-8 Direct Tokio byte stream
Object / Array 200 OK application/json Direct native Rust JSON serializer
Blob / File 200 OK Declared MIME or application/octet-stream Streaming byte buffer
reply(body, opts) Custom (e.g. 201, 400, 404) Inferred or custom headers Direct response wrapper

7. Parameters & Query Strings

Route parameters use :param syntax and are accessed via req.params. Query strings are parsed into req.query:

import { get, reply } from 'nio.js';

// Matches /api/v1/users/usr_101
get('/api/v1/users/:id', ({ params }) => {
  return { requestedUser: params.id };
});

// Matches /search?role=admin&limit=20
get('/search', ({ query }) => {
  const role = query.role || 'all';
  const limit = Number(query.limit || 10);
  return { role, limit };
});

8. Body Parsing (JSON & Multipart)

Request bodies can be consumed exactly once via .json(), .text(), .blob(), or .formData():

import { post, reply } from 'nio.js';

// 1. JSON Body Parsing
post('/api/users', async ({ json }) => {
  const body = await json();
  return reply({ created: body.name }, { status: 201 });
});

// 2. File & Multipart Uploads
post('/api/upload', async ({ formData }) => {
  const form = await formData();
  const file = form.get('file');

  if (!(file instanceof File)) {
    return reply({ error: 'Missing uploaded file' }, { status: 400 });
  }

  return {
    filename: file.name,
    bytes: file.size,
    preview: (await file.text()).slice(0, 100)
  };
});

10. Multi-Worker Execution

Run isolated QuickJS runtimes on worker threads. Configure the worker count with --workers:

# Run with 8 JavaScript workers on port 3000
nio-js run app.ts --port 3000 --workers 8

12. The Hybrid Engine (Zig, Go, Raw C & Python)

NioJS is not just a JavaScript runtime—it is a Hybrid Runtime designed to let you seamlessly blend languages in a single high-throughput event loop, without orchestrating external microservices.

⚡ Zig (High-Speed C-ABI FFI)

Dynamically compile and bind Zig functions directly to QuickJS for cryptographic or mathematical offloading.

import { verify_signature } from './crypto.zig';
const isValid = verify_signature(tx.amount, tx.hash);

☁️ Go (Cloud-Native Networking)

Utilize Go's cgo to build shared libraries, instantly granting your TypeScript backend access to Go's unmatched Kubernetes and gRPC ecosystem.

import { FetchClusterStatus } from './network.go';
const k8sStatus = JSON.parse(FetchClusterStatus());

💾 C (Shared Library Imports)

A system C compiler builds local C sources into shared libraries during preparation. Capsules embed the resulting library, so deployment does not require the compiler.

import { parse_legacy_sensor } from './legacy_parser.c';
const voltage = parse_legacy_sensor(420.5, 1.05);

🧠 Python (In-Process AI Inference)

Run machine learning models natively alongside your JS router via PyO3, sharing memory space without IPC overhead.

import { predict_fraud } from './ml_model.py';
const risk = predict_fraud(tx.amount, tx.account_age);

🦀 Rust (Native Loop Offloading)

Use the /** @native */ directive to have the Rust host automatically compile your heavy JS math loops into machine code.

/** @native */
function scan_history(iterations: number): number {
  let flagCount = 0;
  for (let i = 0; i < iterations; i++) {
    flagCount = (flagCount * 31 + i) & 0x7fffffff;
  }
  return flagCount;
}

13. Zero-Node Dependencies & Lockfiles

No package.json install steps or bloated node_modules. Import standard ES modules over HTTPS:

import { get } from 'nio.js';
import { z } from 'https://esm.sh/zod@3.23.8?target=es2022';

const Schema = z.object({ id: z.string() });
get('/validate', ({ query }) => ({ valid: Schema.safeParse(query).success }));

Lockfile Lifecycle

# Build and generate or update nio.lock
nio-js build app.ts --update -o app.njs

# Strictly enforce cached hashes in CI/CD (fails if checksum mismatch)
nio-js build app.ts --frozen -o app.njs

# Offline & air-gapped production builds (zero network requests)
nio-js build app.ts --offline --frozen -o app.njs

14. Single-File Capsules (.njs)

Build once. Deploy one file. Package your service's precompiled modules, prepared dependency graph, and selected assets into one application artifact. Sign it with your release key and run it on a matching target, or embed it into a standalone executable.

nio-js build app.ts -o dist/app.njs
nio-js run dist/app.njs --port 8080

A capsule needs a matching NioJS runtime version, OS, and CPU architecture. Publisher signing is optional; trusted public-key verification establishes who signed your release.

Explore the complete capsule guide →

15. Agent Diagnostics & Stdio MCP

Engineered specifically to support autonomous agents like Antigravity, Claude, and Cursor:

Fast Structured Diagnostics (nio-js check)

nio-js check src/app.ts --format=agent-json
{
  "valid": true,
  "modules_count": 4,
  "errors": []
}

Stdio Model Context Protocol (nio-js mcp)

Expose compile, syntax check, and isolated code evaluation tools directly to AI coding agents over standard JSON-RPC:

nio-js mcp

16. Real-World Production Examples

Explore production-tested code directly inside the repository:

17. Ecosystem Roadmap to v1.0.0

NioJS is engineered to operate seamlessly as the execution tier of the wider Nio platform:

Milestone Focus Area Key Features
v0.3.0 (Current) Hybrid Engine & Capsule v2.0 Multi-language FFI (Rust, Zig, Python, Go, Raw C), AOT QuickJS bytecode, Ed25519 signatures.
v0.4.0 Streaming & Agent Protocols Server-Sent Events (SSE) token streaming, WebSockets, W3C Trace Context.
v0.5.0 nio-db Native Data Tier Direct import { db } from 'nio.js', live SSE mutation consumer, in-memory query cache.
v0.6.0 nio Agent & Event Bus Event workers (on()), unified tool registry (tool()) for stdio MCP.
v0.7.0 Resilience & Scaffolding Zero-downtime hot reloading, Tokio static file serving, nio-js init task runner.
v1.0.0 General Availability (GA) Frozen Capsule v2.0 spec, cross-ecosystem integration tests.

For deep technical details on the roadmap, see the full ROADMAP_V1.md document.

18. Security, Limits & FAQ

Q: Why does nio-js run reject routes registered after startup?

Routes must be registered synchronously during entry evaluation. Dynamically mutating routing tables at request time introduces concurrency races and degrades performance.

Q: What are the default resource boundaries?

Each QuickJS runtime instance defaults to a 32 MB heap ceiling and a 10 MB maximum request payload. Memory caps prevent rogue scripts from destabilizing the host.

Q: Can I run existing npm modules?

Yes. Any ESM module published to npm can be imported via https://esm.sh/<pkg>. Pure JavaScript and Web standard modules work out of the box.

Q: How does the Hybrid Engine share memory between languages?

HTTP payloads are routed via QuickJS. Native imports use a restricted C ABI with zero to four double arguments and a double result. Go also supports owned C string results. Python arguments and results use JSON through PyO3.

Q: Is NioJS meant to replace Next.js or Nuxt?

No. NioJS is a backend worker runtime, optimized for high-throughput HTTP APIs and AI agent execution. For full-stack apps, you should build your frontend (Vue/React) statically and serve it alongside your NioJS backend API.

Q: What exactly is a .njs capsule?

A capsule is a single-file deployment artifact. nio-js build compiles your TypeScript/JavaScript into Ahead-of-Time (AOT) QuickJS bytecode and bundles it alongside downloaded ESM dependencies, FFI bindings, and static assets into one immutable binary payload. This binary runs without npm install on the target server. Publisher signing is optional; trusted public-key verification establishes publisher identity.

Q: How does /** @native */ differ from Zig FFI?

/** @native */ is a zero-config directive that tells the Rust host to dynamically compile your JavaScript math loops into machine code. Zig FFI is used when you explicitly want to write raw C/Zig code and bind it manually to your project.

Q: Does NioJS support WebSockets?

WebSocket and SSE (Server-Sent Events) streaming support are currently in active development and scheduled for the next major release milestone.