Skip to content

Validation

Francisca Portugal edited this page Oct 27, 2026 · 1 revision

Three validators with three different jobs: Elysia t for 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.

HTTP input: Elysia t

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

Coercion and shapes

  • Query strings are coerced. ?year=2025 satisfies t.Integer(); the handler receives a number. Do not Number() it again.
  • t.Optional is “may be absent”, not “may be null”. For a present-but-null value use t.Union([t.String(), t.Null()]), as Faculty.name and User.email do.
  • Literals and unions narrow the domain. semester is t.Union([t.Literal(1), t.Literal(2)]), and role is one literal per UserRole — 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.

What invalid input becomes

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

What t does not decide

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.

Response schemas

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 }).

Environment: varlock

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 named VITE_*.
  • Never read import.meta.env for config. "false" is a truthy string. Use ENV from varlock/env. One legacy exception remains: Sentry.init reads import.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.ts turns process.env into a typed AuthConfig; routes receive it, they do not read the environment.

Frontend forms: Zod

Zod is a UI concern here, not an API validator:

  • FeedbackReport uses z.object({ email?, description: z.string().trim().min(1) }) with zodResolver and React Hook Form.
  • ExchangeSubmissionConfirmation validates 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.

Contract types vs wire types

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.

Test it at the edge

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 → 404 with 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.

Checklist for a new route

  • 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, the 401, the 404 and the happy shape
  • Update the resource page if the wire shape changed

Pitfalls

  • t.Optional ≠ nullable. Use a union for null.
  • Do not re-parse what Elysia coerced. params.id is 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 t and 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.

See also


Last verified: 2026-10-27

Clone this wiki locally