4 · Middleware & sessions

Middleware runs before your handlers. In nyx-serve a middleware is just a function Request → Response with one rule: return status 0 to continue (and any headers you set still reach the final response), or any other status to stop the request right there.

An auth gate

fn require_auth(req: Request) -> Response {
    let token: String = http_find_header(req.headers_flat, "Authorization")
    if token.length() == 0 {
        return response_json(401, "{\"error\":\"unauthorized\"}")
    }
    return Response { status: 0, headers_flat: [], body: "" }  // continue
}

Register it with app_use. Order matters — middleware runs top to bottom:

cors_configure("*", "GET, POST, OPTIONS", "Content-Type, Authorization")
app_use(app, mw_cors)        // built-in CORS
app_use(app, require_auth)   // your gate

Note you pass the function by name, not called: app_use(app, mw_cors), not mw_cors(). And the CORS origin is set once with cors_configure, not as an argument.

Sessions

Cookie sessions live in std/session, backed by nyx-kv over RESP. Point it at your KV instance once, then session_start issues the cookie and session_set / session_get store per-user values.

import "std/session"

fn login(req: Request) -> Response {
    if not req.form.contains("name") {
        return response_json(400, "{\"error\":\"name is required\"}")
    }
    let name: String = req.form.get("name")
    var resp: Response = response_json(200, "{\"ok\":true}")
    let sid: String = session_start(req, resp)   // sets the cookie
    session_set(req, "user", name)
    return resp
}

fn profile(req: Request) -> Response {
    let user: String = session_get(req, "user")
    if user.length() == 0 {
        return response_json(401, "{\"error\":\"log in first\"}")
    }
    return response_json(200, "{\"user\":\"" + user + "\"}")
}

fn main() {
    session_configure("127.0.0.1", 6380, 3600)  // kv host, port, ttl
    let app: App = app_new()
    app_post(app, "/login", login)
    app_get(app, "/profile", profile)
    serve_app(app, 3000, 8)
}

You need a running nyx-kv for this. The quickest way:

$ docker run -p 6380:6380 nyxlang/nyx-kv   # or point session_configure at nyxkv.com
Sessions survive redirects — the Set-Cookie header is preserved on 3xx responses, so a login that redirects home still logs the user in.