NNextsAI Docs

Native backend development and packaging

Build a Web UI with a Rust worker, implement RPC, prepare production packages, install locally, and integrate local engines.

This tutorial builds a mini app whose Web UI calls Rust's demo.echo. Nexts starts the packaged executable directly and communicates over stdio. Go/C/C++ backends can implement the same protocol.

Prepare a Nexts build with managed-worker/native support, Node.js/npm, and a Rust toolchain. These build steps target Windows x64; build and adjust mappings separately for other platforms. See runtime selection and the integration contract.

1. An independent source project

native-demo/
├─ .nexts-app/app.json
├─ index.html
├─ src/main.ts
├─ vite.config.mjs
├─ package.json
└─ core/
   ├─ Cargo.toml
   └─ src/main.rs

In a new project directory:

npm init -y
npm install @nextsai/app-sdk@1.0.0
npm install --save-dev vite typescript

vite.config.mjs:

import { defineConfig } from 'vite';
export default defineConfig({ base: './' });

index.html (translate the labels for your audience):

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Native Demo</title>
  </head>
  <body>
    <label for="text">Text</label>
    <input id="text" value="hello" />
    <button id="send" disabled>Call Rust</button>
    <pre id="result">Open inside Nexts.</pre>
    <script type="module" src="./src/main.ts"></script>
  </body>
</html>

src/main.ts:

import { defineApp, nexts } from '@nextsai/app-sdk';

const input = document.querySelector<HTMLInputElement>('#text')!;
const send = document.querySelector<HTMLButtonElement>('#send')!;
const output = document.querySelector<HTMLPreElement>('#result')!;
defineApp({ activate() {}, deactivate() {} });

void nexts.ready().then(() => {
  send.disabled = false;
  output.textContent = 'Ready';
}).catch((error: unknown) => { output.textContent = String(error); });

send.addEventListener('click', async () => {
  send.disabled = true;
  try {
    const result = await nexts.backend.invoke<{ text: string }>(
      'demo.echo', { text: input.value },
    );
    output.textContent = result.text;
  } catch (error) {
    output.textContent = String(error);
  } finally {
    send.disabled = false;
  }
});

A Vite browser preview can check layout but has no real Nexts Bridge. Keep an unavailable state and verify backend calls after installation.

2. Rust worker

core/Cargo.toml:

[package]
name = "demo-worker"
version = "0.1.0"
edition = "2021"

[dependencies]
serde_json = "1"

core/src/main.rs:

use serde_json::{json, Value};
use std::{env, io::{self, BufRead, Write}};

fn dispatch(request: &Value, app: &str, instance: &str)
    -> Result<Value, (&'static str, &'static str)>
{
    if request["jsonrpc"] != "2.0"
        || request["context"]["sdkVersion"] != "1.0.0"
    {
        return Err(("unsupported_protocol", "Unsupported protocol or SDK"));
    }
    if request["context"]["appId"] != app
        || request["context"]["instanceId"] != instance
    {
        return Err(("identity_mismatch", "Application identity mismatch"));
    }
    match request["method"].as_str() {
        Some("demo.capabilities") => Ok(json!({"methods":["demo.echo"]})),
        Some("demo.echo") => {
            let text = request["params"]["text"].as_str()
                .ok_or(("invalid_params", "text must be a string"))?;
            if text.len() > 65536 {
                return Err(("invalid_params", "text exceeds 64 KiB"));
            }
            Ok(json!({"text": text}))
        }
        _ => Err(("method_not_found", "Unknown application method")),
    }
}

fn required_env(name: &str) -> io::Result<String> {
    env::var(name).map_err(|_| io::Error::new(
        io::ErrorKind::InvalidInput, format!("Missing {name}"),
    ))
}

fn main() -> io::Result<()> {
    let app = required_env("NEXTS_APP_ID")?;
    let instance = required_env("NEXTS_APP_INSTANCE_ID")?;
    if required_env("NEXTS_APP_RPC_PROTOCOL")? != "nexts-app-rpc-v1" {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "Unsupported RPC"));
    }
    let stdin = io::stdin();
    let mut stdout = io::stdout().lock();
    for line in stdin.lock().lines() {
        let line = line?;
        let request: Value = match serde_json::from_str(&line) {
            Ok(value) => value,
            Err(_) => {
                eprintln!("Invalid RPC JSON");
                break;
            }
        };
        match request["method"].as_str() {
            Some("app.shutdown") => break,
            Some("$/cancelRequest") => continue,
            _ => {}
        }
        let Some(id) = request["id"].as_str() else {
            eprintln!("RPC requires a string id");
            break;
        };
        let response = match dispatch(&request, &app, &instance) {
            Ok(result) => json!({"jsonrpc":"2.0", "id":id, "result":result}),
            Err((code, message)) => json!({
                "jsonrpc":"2.0", "id":id,
                "error":{"code":code,"message":message}
            }),
        };
        writeln!(stdout, "{response}")?;
        stdout.flush()?;
    }
    Ok(())
}

This minimal example handles immediate read-only methods. Add persistence, task queues, idempotency, and cooperative cancellation for production. Ignoring cancellation notifications, as this synchronous example does, is unsuitable for long-running work. Place databases in NEXTS_APP_DATA_DIR, never the source directory, installed package, or Nexts product database.

3. Complete manifest

.nexts-app/app.json:

{
  "schemaVersion": 2,
  "id": "ai.nexts.native-demo",
  "name": "Native Demo",
  "version": "0.1.0",
  "description": "A Web UI calling a packaged Rust worker.",
  "author": { "name": "Your Name" },
  "kind": "app",
  "views": [{
    "id": "main", "title": "Native Demo", "surface": "window",
    "entry": { "type": "web", "path": "dist/index.html" }
  }],
  "runtime": {
    "type": "managed-worker", "engine": "native",
    "entry": "bin/win32-x64/demo-worker.exe",
    "platforms": { "win32-x64": "bin/win32-x64/demo-worker.exe" },
    "protocol": "nexts-app-rpc-v1", "lifecycle": "on-demand",
    "healthTimeoutMs": 10000, "shutdownTimeoutMs": 5000,
    "resources": {
      "memoryMb": 256, "cpuPercent": 50, "maxProcesses": 1,
      "timeoutMs": 30000, "maxOutputBytes": 4194304
    }
  },
  "storage": {
    "ownership": "application", "mount": "/data",
    "database": "data/app.sqlite", "backupBeforeUpdate": true
  },
  "network": { "outboundDomains": [], "loopback": false },
  "permissions": [{
    "key": "agent.integration", "optional": true,
    "reason": "Expose the demo's read-only methods to the assistant"
  }],
  "agentIntegration": {
    "enabledByDefault": false,
    "discoveryAction": "demo.capabilities",
    "actions": [
      {
        "name": "demo.capabilities", "method": "demo.capabilities",
        "description": "List available methods", "access": "read",
        "inputSchema": { "type": "object", "properties": {}, "additionalProperties": false }
      },
      {
        "name": "demo.echo", "method": "demo.echo",
        "description": "Return the supplied text", "access": "read",
        "inputSchema": {
          "type": "object", "properties": { "text": { "type": "string" } },
          "required": ["text"], "additionalProperties": false
        }
      }
    ]
  }
}

For UI-only use, remove both agentIntegration and its permission. Before release, add engine.nexts using the actual minimum client version you tested, and engine.appSdk: "^1.0.0". Do not advertise compatibility with an older host lacking native workers.

4. Build and stage production files

Run in the project root:

cargo build --release --manifest-path core/Cargo.toml
npx vite build

Create a fresh versioned staging directory in PowerShell:

$stagePath = 'release/0.1.0'
New-Item -ItemType Directory -Force "$stagePath/.nexts-app", "$stagePath/bin/win32-x64", "$stagePath/dist" | Out-Null
Copy-Item -LiteralPath '.nexts-app/app.json' -Destination "$stagePath/.nexts-app/app.json"
Copy-Item -Path 'dist/*' -Destination "$stagePath/dist" -Recurse -Force
Copy-Item -LiteralPath 'core/target/release/demo-worker.exe' -Destination "$stagePath/bin/win32-x64/demo-worker.exe"

Include only the manifest, frontend build, native entries, required resources/libraries, and licenses. Exclude core/target, node_modules, development databases, tokens, and the full source workspace.

Under Apps → Add → Install from local directory, select release/0.1.0. Open the app and select Call Rust; verify the input is returned. Closing the window may leave the backend running. Use the explicit Stop action to verify process exit, then open again.

To create a ZIP, ask the Nexts assistant to use validate_nexts_app and package_nexts_app inside this source workspace, targeting release/0.1.0. These are tool names, not terminal subcommands. Packaging checks every platform entry and generates a ZIP, SHA-256 checksum, and basic CycloneDX SBOM. Publishers must complete native dependency and license inventories; the basic SBOM does not fully analyze Cargo/Go/C++ dependencies.

Submit production ZIP and SBOM through Apps → My submissions. Packaging does not publish. Increment the version for each change, rebuild, reinstall, and verify; never edit an installed immutable package in place.

Select Managed worker (Python / Node.js / native) in the submission form. Keep runtime.type: "managed-worker" and runtime.engine: "native" in the package. For a manual admin entry, choose the Nexts package distribution and Managed worker runtime. Approved releases remain managed-worker in the catalog. The signed app.json defines the engine and platform entries; there is no separate native runtime type.

The admin's Managed native program distribution manages a standalone native window or background program. It is a separate distribution from this WebView + native worker example. Set supported platforms, architectures, and the minimum Nexts version to match the bundled artifacts and the client versions you have verified.

5. Platform distribution

Provide an executable matching each platform/architecture. Mapping keys use win32 / darwin / linux and x64 / arm64. They are not Rust target triples: an x86_64-pc-windows-msvc artifact belongs under win32-x64.

For Windows-only releases, declare only Windows. For multiplatform packages, include every mapped artifact. Account for macOS signing and dynamic libraries, and Linux libc/library compatibility. Nexts does not cross-compile, install missing system dependencies, or bypass OS signing checks.

Windows starts the .exe directly. Unix installation sets executable bits only on validated native entries. Entries must remain within the immutable package; absolute paths, traversal, and escaping symlinks are rejected. Runtime declarations accept no free-form shell, argument, or environment templates.

6. Local engines such as ComfyUI

A native worker can manage connections, tasks, and app-private state. ComfyUI still needs its own Python/model environment; account for both processes' requirements.

  1. Call the worker through nexts.backend.invoke and stdio. Remove development-proxy dependencies from production.
  2. Declare network.loopback: true for local connections, enumerate required outbound domains for downloads, and enforce the policy in the worker.
  3. Read a declared business capability such as engine.local from NEXTS_APP_PERMISSIONS. The host does not set COMFY_STUDIO_LOCAL_ENGINE; translate configuration in your own adapter if needed.
  4. Have users select and confirm the engine executable, working directory, and model directories. Validate canonical paths in the backend and protect other applications' and host data.
  5. Size maxProcesses, memoryMb, and cpuPercent for the actual workload. maxProcesses: 1 allows only the worker. Windows memory/CPU limits cover the whole Job. The example's 256 MiB is unsuitable for a large local-model engine, and this field does not limit GPU memory.
  6. Implement engine startup, downloads, and generation as durable application tasks. Return task IDs, expose status/cancel actions, and inspect uncertain status before resubmitting.

Installation does not run dependency-install scripts. User-initiated engine setup, dependency management, and downloads must be explicit application operations with their own task and diagnostic records.

7. Verification and troubleshooting

CheckExpected behavior
Manifest/platformThe current platform and every declared artifact exist
First RPCMatching identity, string IDs, and clean stdout
ErrorsUseful feedback for invalid parameters, unknown methods, crashes, and timeouts
Cancel/stopCooperative cancellation; managed processes exit on explicit stop
PersistenceUpgrades preserve data; business writes never modify the package
AgentOnly declared actions are discoverable; UI and Agent share business data
Production packageRuns without the source workspace or development server

unknown variant native indicates an old host. does not support platform means a missing platform mapping. Missing entries usually indicate staging/path mistakes. For immediate exit, inspect runtime.stderr.log, libraries, architecture, and limits. For stalled RPC, check flushing, stdout contamination, and string IDs.

On this page