Repository navigation
Validation
Three validators with three different jobs: Elysia
tfor HTTP, varlock for environment variables, Zod for frontend forms. They are not interchangeable. Status: current.
| Layer | Tool | Validates | On failure |
|---|---|---|---|
| HTTP request/response | Elysia t
|
Params, query, body, cookies, response shape |
422 validation-error, or 500 for a bad response |
| Environment | varlock (.env.schema) |
Types, required values, public/sensitive split | Process/build refuses to start |
| Frontend forms | Zod + React Hook Form | User input before submit | Inline form errors |
| Business rules | Application code | Semantics (state, ownership, eligibility) |
400/403/409 via HttpError
|
There is no Zod in the backend. Its package.json has varlock, not Zod: HTTP validation is
Elysia's built-in t, which also drives the OpenAPI document and the Eden types.
Every route declares the parts of the request it reads:
params: t.Object({ id: t.Integer() })
query: t.Object({ year: t.Optional(t.Integer()), faculty: t.Optional(t.String()) })
body: t.Object({ username: t.Optional(t.String()), password: t.Optional(t.String()) })
cookie: t.Cookie({ session: t.Optional(t.String()) })Where they live:
| Shape | Location |
|---|---|
Shared entity schemas (Course, CourseUnit, Occurrence, Faculty) |
src/interface/routes/catalog.schemas.ts |
Session shapes (sessionUser, anonymous, legacySessionInfo) |
src/interface/routes/auth/auth.schemas.ts |
Route-specific params / query / body / cookie
|
inline on the route |
Error body ({ error, code }) |
apiError in interface/middleware/error-handler.ts
|
-
Query strings are coerced.
?year=2025satisfiest.Integer(); the handler receives a number. Do notNumber()it again. -
t.Optionalis “may be absent”, not “may be null”. For a present-but-null value uset.Union([t.String(), t.Null()]), asFaculty.nameandUser.emaildo. -
Literals and unions narrow the domain.
semesterist.Union([t.Literal(1), t.Literal(2)]), androleis one literal perUserRole— a new role without a matching literal is a compile error. -
Arrays and comma lists need an explicit schema. No implemented route takes them; the planned
admin filters (
activeStates=untreated,treated) will have to split and validate.
?year=abc, /v1/courses/abc, malformed JSON
→ 422 { "error": "Request failed validation", "code": "validation-error" }
The route never runs. Elysia rejects the request and the global onError hook normalizes the
body. Tests assert this explicitly:
it('a non-numeric course id is rejected by the params schema, not the handler', async () => {
const { status } = await get('/v1/courses/abc')
expect(status).toBe(422)
})Input validation runs before the required-session guard, so an anonymous request with a
malformed id is 422, not 401.
A schema says “year is an integer”, not “this course exists” or “you may read it”. Those are route
or use-case decisions and produce 404, 403, 409, etc. See
Error handling.
Every route declares what it returns:
response: { 200: courseSchema, 404: 'ApiError' }Two consequences:
- Fields not in the schema are stripped. A new column never leaks by accident; add it to the schema deliberately.
-
A response that fails its own schema is a bug, not the caller's fault: it is logged and
answered with
500 internal-error.
302 responses declare t.Void() for documentation only — redirect() bypasses validation
(and the OpenAPI plugin removes the invalid content: { type: 'void' } from the spec).
'ApiError' is a named model registered per route instance. Elysia does not inherit the
app-level model registration into standalone plugins, so each route group calls
.model({ ApiError: apiError }).
Both apps declare their environment in a committed .env.schema. Local values go in a
git-ignored .env; the schema is the contract.
# @defaultRequired=infer
# @defaultSensitive=true
DATABASE_URL="postgresql://tts:tts@localhost:5434"| Frontend | Backend |
|---|---|
@defaultSensitive=inferFromPrefix(VITE_) |
@defaultSensitive=true |
@generateTsTypes(path=src/env.d.ts) |
types come from NodeJS.ProcessEnv
|
Read through ENV from varlock/env
|
Read through process.env inside core/config
|
Inlined at build time by varlockVitePlugin
|
Checked when the script runs under varlock run
|
Annotations that matter:
| Annotation | Effect |
|---|---|
@type=port, @type=boolean, @type=url, @type=enum(…), @type=string(matches=…)
|
Shape validation |
@public |
Allowed in the browser bundle (frontend) |
@sensitive |
Must never reach the client / a log |
@required |
No default; the process fails without it |
@defaultRequired=infer |
Anything with a default is optional |
Rules:
-
Only
VITE_-prefixed values are public. Everything else is a secret; a backend secret must never be namedVITE_*. -
Never read
import.meta.envfor config."false"is a truthy string. UseENVfromvarlock/env. One legacy exception remains:Sentry.initreadsimport.meta.env.VITE_APP_SENTRY_DSN. - A bad value fails fast. varlock validates before the app starts (backend) or before the build completes (frontend), so a typo is a boot error, not a runtime surprise.
-
Config is parsed in one place.
core/config/auth.tsturnsprocess.envinto a typedAuthConfig; routes receive it, they do not read the environment.
Zod is a UI concern here, not an API validator:
-
FeedbackReportusesz.object({ email?, description: z.string().trim().min(1) })withzodResolverand React Hook Form. -
ExchangeSubmissionConfirmationvalidates the exchange message conditionally.
const form = useForm<z.infer<typeof schema>>({ resolver: zodResolver(schema) })The server validates the same request independently. A form schema is there to give immediate feedback and keep invalid requests from being sent — it is not a security boundary.
The Prisma 8 contract is the database truth; it is not the API shape.
| Layer | Type | Example |
|---|---|---|
| Database | generated contract types | semester: number |
| Repository | domain port type | semester: 1 | 2 |
| Route | Elysia t schema |
t.Union([t.Literal(1), t.Literal(2)]) |
The repository narrows at the boundary (toCourseUnitSemester), the route validates the wire shape,
and the response schema strips anything undeclared. Never return a raw database row and assume the
contract is the API.
Route tests drive the real app through createApp().handle(request) with fake repositories, so
validation is exercised exactly as a client sees it:
- malformed id/year →
422; - missing cookie →
401; - unknown id →
404with the domain code; - response shape → assert the exact JSON, which catches an accidentally stripped field.
Helpers: VALIDATION_ERROR_BODY, UNAUTHORIZED_BODY in
tests/interface/routes/support/catalog-test-utils.ts.
- Declare every input it reads:
params,query,body,cookie - Declare the full success shape in
response - Declare
'ApiError'on every documented failure status - Put semantic checks in the route/use-case, not in the schema
- Use a domain code for a failure the client must distinguish
- Test the
422, the401, the404and the happy shape - Update the resource page if the wire shape changed
-
t.Optional≠ nullable. Use a union fornull. -
Do not re-parse what Elysia coerced.
params.idis already a number. - Unknown response fields disappear. If a field is missing in production, check the schema first.
-
Response-schema failures are
500s. They are bugs, not client errors. -
Zod is not the backend validator. Adding it to a route would duplicate
tand break the OpenAPI/Eden generation. - Env changes need a restart or rebuild. Frontend values are inlined at build time.
-
A secret in a
VITE_var is public. Rename it, rotate it, and check the bundle.
- Error handling — 422 vs 400, codes and the handler
- Request lifecycle — where validation runs
- Adding an endpoint — the full route checklist
- Backend layers — where business rules live
- Testing 🚧 · Environment variables 🚧
Last verified: 2026-10-27