Tutorial: Building a Modern Web App

In this tutorial, you will build a high-performance REST API and real-time backend with JSON serialization, route guards, and async I/O in Nyx.

1. Initializing the Web Project

nyx init nyx-web-api
cd nyx-web-api

2. Defining Data Models & JSON Serialization

Create your domain models using Nyx structs:

module models

pub struct Task {
    pub id: i64,
    pub title: String,
    pub completed: bool,
    pub priority: String,
}

pub fn create_task(id: i64, title: String, priority: String) -> Task {
    Task {
        id: id,
        title: title,
        completed: false,
        priority: priority,
    }
}

3. Creating the Async HTTP Server

Set up an async HTTP server with route handlers using std.http and std.json:

import std.http
import std.json
import std.io
import std.vec
import models

pub fn main() {
    let mut router = http.create_router()

    // Health check route
    router.get("/health", |req| {
        http.Response.json("{\"status\":\"healthy\",\"uptime\":3600}")
    })

    // REST Task Endpoint
    router.get("/api/tasks", |req| {
        let t1 = models.create_task(1, "Configure W3C Tracing".to_string(), "HIGH".to_string())
        let t2 = models.create_task(2, "Train SIMD Embedding Model".to_string(), "MEDIUM".to_string())

        let payload = "{\"tasks\":[{\"id\":1,\"title\":\"" + t1.title + "\",\"priority\":\"" + t1.priority + "\"}," +
                      "{\"id\":2,\"title\":\"" + t2.title + "\",\"priority\":\"" + t2.priority + "\"}]}"
        
        http.Response.json(payload)
    })

    // Server-Sent Events (SSE) stream
    router.get("/api/stream", |req| {
        let mut res = http.Response.sse()
        res.send_event("message", "Live cluster metrics connected.")
        res
    })

    std.io.println("🚀 Nyx Web Server listening on http://127.0.0.1:8080")
    http.listen_and_serve("127.0.0.1:8080", router)
}

4. Running and Testing

Compile and launch the server:

nyx run src/main.nyx

Test your endpoint via curl:

curl -i http://127.0.0.1:8080/api/tasks

5. Compiling to WebAssembly (WASM)

Nyx compiles directly to standalone WebAssembly modules with zero runtime overhead:

nyx build --target wasm32 -o dist/app.wasm