KryonOSDocs
Connectivity & Networking

Embedded HttpServer

Express-style embedded HTTP web server running directly on ESP32.

11. Web Server API (HttpServer)

KryonOS features a high-performance, Express.js-style embedded HTTP web server (HttpServer) designed specifically for the ESP32-S3 microcontroller architecture. It enables building REST APIs, IoT control dashboards, local web interfaces, and static file servers directly in JavaScript.

11.1 Key Architecture & Safeguards

  • Non-blocking Request State Machine: 500 ms header timeout prevents Slowloris network attacks and prevents the 60 FPS UI/touch loop from freezing.
  • DMA & Internal SRAM Protection: Static file streaming streams in 1024-byte (1 KB) chunks with periodic esp_task_wdt_reset() watchdog feeding.
  • 16 KB Payload Cap: Enforces a hard 16 KB body limit (413 Payload Too Large) in C++ to safeguard Duktape heap against OOM.
  • Path Traversal Security: Protects against .. directory traversal and enforces filesystem sandbox boundaries.
  • Automatic Resource Cleanup: Automatically unrefs all JS callbacks and tears down sockets on app exit.

11.2 Server Lifecycle & Controls

MethodParametersReturn TypeDescription
HttpServer.listen([port=80])port: NumberBooleanStarts listening for HTTP connections on the specified port.
HttpServer.stop()NoneBooleanStops server and frees listening sockets.
HttpServer.isRunning()NoneBooleanReturns true if server is currently active.
HttpServer.getPort()NoneNumberReturns current listening port number.
HttpServer.getURL()NoneStringReturns server URL (e.g. "http://192.168.1.100:80/").
HttpServer.getStats()NoneObjectReturns { requestsHandled, uptimeMs, port, running }.
HttpServer.poll()NoneundefinedPumps pending socket events (also auto-called inside System.delay()).
HttpServer.reset()NoneundefinedClears all registered routes and stops server.

11.3 Routing & Middleware

MethodParametersReturn TypeDescription
HttpServer.on(method, path, callback)method: String, path: String, callback: FunctionundefinedRegisters route for HTTP method ("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "ANY").
HttpServer.get(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for GET route.
HttpServer.post(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for POST route.
HttpServer.put(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for PUT route.
HttpServer.delete(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for DELETE route.
HttpServer.patch(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for PATCH route.
HttpServer.options(path, callback)path: String, callback: FunctionundefinedConvenience shortcut for OPTIONS route.
HttpServer.use(middleware)middleware: Function (req, res)undefinedGlobal middleware executed before route handlers (CORS, logging, auth).
HttpServer.serveStatic(routePrefix, fsPath)routePrefix: String, fsPath: StringBooleanSafely hosts static HTML/CSS/JS/images from LittleFS or SD card with auto-detected MIME types.
HttpServer.notFound(callback)callback: Function (req, res)undefinedCustom 404 handler callback.

11.4 Request Object (req)

The req object passed to route handlers contains:

  • req.method: HTTP method in uppercase ("GET", "POST", etc.)
  • req.url: Full URL string (e.g. "/api/status?verbose=true")
  • req.path: Clean path without query parameters (e.g. "/api/status")
  • req.query: Object containing key-value query parameters (e.g. { verbose: "true" })
  • req.params: Object containing route parameters (e.g. /user/:id -> { id: "42" })
  • req.headers: Request headers map (lowercase keys)
  • req.body: Raw request payload text (strictly capped at 16 KB)
  • req.json(): Helper function returning parsed JSON object from req.body
  • req.ip / req.clientIP: Client IP address string
  • req.getHeader(name): Case-insensitive header lookup helper

11.5 Response Object (res)

The res object provides fluent Express-like response methods:

  • res.status(statusCode): Sets HTTP status code (default 200). Returns res for chaining.
  • res.setHeader(name, value): Sets a response header. Returns res.
  • res.setHeaders(headerMap): Sets multiple response headers. Returns res.
  • res.cors([origin="*"]): Sets standard CORS headers. Returns res.
  • res.send(body, [contentType="text/plain; charset=utf-8"]): Sends response string with Connection: close.
  • res.json(data): Serializes object to JSON and sends with Content-Type: application/json; charset=utf-8.
  • res.html(htmlString): Sends HTML string with Content-Type: text/html; charset=utf-8.
  • res.text(plainText): Sends plain text with Content-Type: text/plain; charset=utf-8.
  • res.sendFile(fsPath, [contentType]): Streams file in 1024-byte chunks with auto MIME detection and watchdog feeding.
  • res.redirect(location, [statusCode=302]): Sends HTTP redirect header.

11.6 Complete Example Application

// Initialize Web Server on Port 80
HttpServer.listen(80);

// Global Middleware for CORS
HttpServer.use(function(req, res) {
    res.cors("*");
    console.log(req.method, req.path, "from", req.ip);
});

// Serve Static HTML/CSS/JS files from SD card
HttpServer.serveStatic("/static", "/sd/www");

// Root Endpoint - HTML Dashboard
HttpServer.get("/", function(req, res) {
    res.html("<h1>KryonOS Web Server</h1><p>Running on ESP32-S3</p>");
});

// REST Endpoint - Device Status
HttpServer.get("/api/status", function(req, res) {
    res.json({
        os: "KryonOS",
        chip: System.getInfo().chipModel,
        freeRAM: System.getInfo().freeRAM,
        temperatureC: System.getTemperature(),
        uptimeMs: System.millis()
    });
});

// Dynamic Route Parameters
HttpServer.get("/user/:id", function(req, res) {
    res.json({
        userId: req.params.id,
        timestamp: System.millis()
    });
});

// POST Endpoint with JSON Payload
HttpServer.post("/api/action", function(req, res) {
    var data = req.json();
    console.log("Received action payload:", data);
    res.status(200).json({ success: true, received: data });
});

// Custom 404 Handler
HttpServer.notFound(function(req, res) {
    res.status(404).json({ error: "Endpoint Not Found", path: req.path });
});

// Main Loop
while (true) {
    var touch = System.getTouch();
    if (touch && touch.touched && touch.x >= 200 && touch.y <= 40) {
        break; // Exit app
    }
    System.delay(20); // Pumps web server events non-blockingly
}

HttpServer.stop();