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
- web.api_key_auth() — returns an extractor that reads an
x-api-keyheader orapi_keyquery param from a request dict. - web.parse_basic_auth(req) — reads an
Authorization: Basic ...header from a request dict into username and password fields, or null. - web.basic_auth(user, pass) — builds an Authorization header dict for outbound requests; it is not a server-side validator.
- web.bearer_auth() — extracts a Bearer token from a request object with
.headers; PeaLang route handlers receive dicts, so readreq["headers"]["authorization"]directly there. - web.request_id() — middleware that adds an
x-request-idheader to the request when registered withapp.use(...).
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
- web.health(payload) — returns a JSON response with
status: okplus any payload fields you pass. - web.pagination(page, per_page, total) — returns a dict with
page,per_page,pages,has_nextandhas_prev;per_pageis capped at 100. - web.envelope(data, meta, ok) and web.with_links(data, links) — consistent JSON envelopes and
_linksfields 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 a route group with
web.rate_limitand observe the rejection once you exceed the limit. - Merge
web.security_headers()into a response and echo thex-request-idfromreq["headers"]into its headers; check both withcurl -I.