PeaBox Lab › PeaLang › Learn › Chapter 28 › Lesson 2

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 helpers you should reach for before you write your own.

Input validation

let schema = {
  "email": { "type": "string", "required": true },
  "age":   { "type": "int", "required": false }
}

app.post("/users", function(req) {
  let parsed = web.validate(req["json"], schema)
  if parsed["ok"] == false {
    return web.validation_error(parsed["errors"])
  }
  return web.json(parsed["data"], 201)
})

For dict input, web.validate returns a dict with ok, errors (a list of strings) and data; for non-dict input it returns only ok and errors. It checks required keys and the declared types — string, number, int, bool, list, object and any. Bounds and patterns are not enforced by this helper, and it returns the input data unchanged; no coercion happens.

Authentication helpers

These helpers extract or build credentials; none of them verifies them for you. Compare the value in your handler and return web.unauthorized() for a missing or invalid credential, or web.forbidden() for a known principal without access. Request header keys are lowercase.

Rate limiting

app.use(web.rate_limit(60, 60))

web.rate_limit(limit, window_seconds) is fixed-window middleware keyed by client address (or x-forwarded-for). Once the window is full the middleware raises, and dispatch turns that into an error response. For a specific 429 with a Retry-After header, build one yourself with web.too_many_requests("Slow down", 60). Decide once whether the limit applies before or after auth, then apply it globally.

Caching, ETags and conditional requests

web.etag(body) returns a response with a hash-derived ETag header; web.not_modified(etag) builds a 304 response. Conditional matching is up to your handler: compare req["headers"]["if-none-match"] and return the 304 when it matches. web.cache_control(300, true, false) returns a Cache-Control: public, max-age=300 header dict; merge it with web.merge_headers(...) and pass it as the third argument to web.json(value, status, headers).

Security headers in one call

let headers = web.security_headers()
# X-Content-Type-Options: nosniff
# X-Frame-Options: DENY
# Referrer-Policy: no-referrer
# Permissions-Policy: geolocation=(), microphone=(), camera=()

web.security_headers() returns a header dict, not middleware — merge it into each response with web.merge_headers(headers, web.cache_control(300, true, false)). The defaults cover the four headers shown; there is no CSP or HSTS entry, so add those explicitly if you need them.

Health, pagination and envelopes

Guided practice

← Previous Next →