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 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

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

Guided practice

← Previous Next →