Part V — The Modern Experience Layer · Chapter 28 · Lesson 2 of 3
Validation, auth, rate limiting and security headers
Routing makes a demo. Validation and auth make a service. This lesson covers the middleware layer you should reach for before you write your own.
Input validation
let schema = {
"email": { "type": "string", "required": true },
"age": { "type": "int", "min": 0, "max": 150 }
}
app.post("/users", fn(req) {
let parsed = web.validate(req.json, schema)
if parsed.ok == false {
return web.validation_error(parsed.errors)
}
return create_user(parsed.value)
})
web.validate returns a result object — check ok, use parsed.errors for the field-level report, parsed.value for the coerced output. The validator does types, bounds, string patterns and required keys — it is not a full JSON Schema engine, and that is a feature: predictable output, no surprising coercions.
Authentication helpers
- web.bearer_auth(fn(token) => claims | null) — validates Authorization: Bearer tokens.
- web.basic_auth(fn(user, pass) => bool) — for internal tools behind a proxy or VPN.
- web.api_key_auth(fn(key) => identity | null) — API keys from a header; hash and compare, never compare plaintext.
- web.request_id() — generates and propagates a request correlation id into logs and response headers.
Failed auth returns web.unauthorized() (missing/invalid) or web.forbidden() (known principal, insufficient scope) — keep those semantics consistent and your clients will thank you.
Rate limiting
app.use(web.rate_limit({ "limit": 60, "window_seconds": 60, "key": "ip" }))
Fixed-window counters keyed by IP, header or token. When the limit trips, clients get web.too_many_requests() with a Retry-After hint. Rate limit before auth for cheap rejection, or after auth for per-user fairness — decide once, apply globally.
Caching, ETags and conditional requests
web.etag(body) computes a weak ETag; web.not_modified() answers 304 when If-None-Match matches. Pair web.cache_control("public, max-age=300") with content hashing for assets and you have a correct caching story with three calls.
Security headers in one call
app.use(web.security_headers())
# X-Content-Type-Options: nosniff
# X-Frame-Options: DENY
# Referrer-Policy: strict-origin-when-cross-origin
# Content-Security-Policy: default-src 'self'
# Strict-Transport-Security (behind TLS)
One call, sane defaults, no configuration drift. If you need a custom CSP, pass it to the helper — do not hand-write eight header lines that you will forget to audit.
Health, pagination and envelopes
- web.health(fn() => ok) — /healthz-style readiness with a dependency check.
- web.pagination(query) — parses
?page=&page_size=into a safe, bounded structure. - web.envelope(data) / web.with_links(data, links) — consistent API envelopes, HATEOAS-style link headers where you need them.
Guided practice
- Add a validation schema to one POST route and return
web.validation_errorwith two field errors; confirm the shape in curl. - Protect
/api/v1/*withweb.rate_limitand observe the 429 with Retry-After. - Add
web.security_headers()andweb.request_id()globally; check response headers withcurl -I.