Nyx by Example

Serve CORS

CORS middleware handles preflight OPTIONS and adds Access-Control-* headers to responses. cors_configure sets the allowed origin, methods, and headers. Middleware chains apply in registration order.

Code

// nyx-serve CORS — cross-origin headers for frontend APIs
// CORS nyx-serve — headers cross-origin para APIs de frontend

import "std/http"
import "std/web"

fn api_data(req: Request) -> Response {
    return response_json(200, "{\"data\": [1, 2, 3]}")
}

fn main() -> int {
    let app: App = app_new()

    // Configure CORS policy — who can call the API, what methods, headers
    cors_configure(
        "https://myapp.com",
        "GET, POST, PUT, DELETE",
        "Content-Type, Authorization, X-API-Key"
    )

    // Register CORS middleware — handles OPTIONS preflight + adds headers
    app_use(app, mw_cors)

    // Also register logging middleware
    app_use(app, mw_logging)

    app_get(app, "/api/data", api_data)

    print("CORS configured for https://myapp.com")
    print("middleware chain: logging -> cors -> route handler")
    print("OPTIONS preflight requests return 204 with appropriate headers")
    return 0
}

Output

CORS configured for https://myapp.com
middleware chain: logging -> cors -> route handler
OPTIONS preflight requests return 204 with appropriate headers

Explanation

Browsers enforce the same-origin policy on XHR and fetch — a site at myapp.com can't call api.myapp.com unless the server opts in. CORS is the opt-in protocol: the browser sends an OPTIONS preflight asking "can I?", and the server answers with Access-Control-Allow-* headers. mw_cors handles both halves: it short-circuits OPTIONS with a 204 and the configured headers, and stamps every real response with Access-Control-Allow-Origin. cors_configure centralizes the policy so you never hardcode it in a handler. The middleware chain runs in registration order — logging observes every request before cors rewrites it, which is usually what you want.

← Previous Next →

Source: examples/by-example/83-serve-cors.nx