How input becomes a value the app trusts, and how that value reaches storage. Read this when the task involves:
- Defining database tables, columns, relations, and migrations
- Querying or mutating persisted data with `Database`
- Parsing and validating user input from forms, query strings, or external payloads
- Choosing between schema-level checks, table validation hooks, and migration-level constraints
For where validation runs in the request lifecycle, see `routing-and-controllers.md`. For session or identity-bound writes, see `auth-and-sessions.md`.
## Table Definitions (`remix/data-table`)
Define tables with typed columns, relations, and optional validation hooks:
Composite primary keys go on the table option, not the column: `primaryKey: ['order_id', 'book_id']`.
### Schema vs migrations
Column modifiers on runtime `table(...)` definitions in `app/data/schema.ts` describe app-facing column metadata. They do not create or update database tables by themselves. The source of truth for actual DDL and constraints is your hand-written SQL migration files. Two valid patterns:
- **Mirror constraints in schema and SQL** — table definitions stay useful as schema-level docs, and migrations still own the actual DDL.
- **Bare columns in schema, constraints in SQL** — schema describes what the app reads and writes; migrations own the DDL and constraints.
Pick one and apply it consistently across the app.
### Table lifecycle hooks
Tables can define validation and lifecycle hooks:
-`validate` runs before `create` and `update` writes and should return either `{ value }` or `{ issues }`
-`beforeWrite` can normalize or veto `create`/`update` values
`createSqliteDatabase` accepts synchronous SQLite clients with a shared `prepare`/`exec` surface, including Node's `node:sqlite`, Bun's `bun:sqlite`, and compatible clients. Use whichever client fits the runtime instead of assuming `better-sqlite3` is required.
Migrations are plain SQL files. Each migration is a directory named `YYYYMMDDHHmmss_<slug>/` containing a hand-written `up.sql` (required) and an optional `down.sql` (omit for irreversible migrations).
```txt
db/
migrations/
20260228090000_create_users/
up.sql
down.sql
20260301083000_add_books_search_index/
up.sql
```
### Writing migrations
Write standard SQL in `up.sql` and `down.sql`:
```sql
-- up.sql
createtableusers(
idintegerprimarykeyautoincrement,
emailtextnotnullunique,
nametextnotnull
);
createindexusers_email_idxonusers(email);
```
```sql
-- down.sql
droptableifexistsusers;
```
Do **not** import app code (e.g. `app/data/schema.ts`) into migration files. Migrations must be stable, immutable artifacts — importing live schema definitions creates drift between what the migration meant when it was written and what it does when replayed later. SQL files guarantee stability because they cannot import anything.
Migrations run inside a transaction by default (when the database supports transactional DDL). Override per migration with a directive comment in `up.sql`:
Use `data-schema` to validate user input (forms, query params, API payloads). This is separate from table-level `validate` hooks which run at persistence.
### Reading FormData: middleware vs `request.formData()`
There are two ways to get a `FormData` value inside an action.
The recommended way: register `formData()` middleware in the root stack and read with `get(FormData)`. The body is parsed once per request, and the typed `FormData` value flows through the context system. This also lets `methodOverride()` and CSRF middleware work uniformly.
```typescript
import{formData}from'remix/middleware/form-data'
letrouter=createRouter({
middleware:[,/* ... */formData()/* ... */],
})
// In an action:
letparsed=s.parseSafe(signupSchema,get(FormData))
```
The fallback: `await request.formData()` directly. This works without middleware and is fine for small one-off cases, but it bypasses the context system, runs once per call site, and doesn't compose with middleware that depends on parsed form fields.
### Safe parsing
`s.parse` throws on invalid input. `s.parseSafe` returns a tagged result and is usually what an action wants, since validation failure is an expected outcome (re-render the form with errors) rather than an exception:
Returning a `Response` for validation failures keeps the route contract honest: the same action returns 200 on success, 400 with errors on bad input, no out-of-band exception flow.
### Transforming validated output
Use `.transform(...)` when a schema should validate one shape but return another value or output type. Transforms run after validation and compose with `.pipe(...)` and `.refine(...)`:
Avoid these shapes when reading and validating input:
- **Raw `formData.get('name')` plus an `if (typeof name !== 'string')` guard**, then a thrown custom error. This reinvents what `data-schema` already does, loses the typed result, and pushes error translation into a `try/catch` instead of a return value.
- **Letting route-local domain errors leak out of the action.** Translate expected outcomes (bad input, missing record, duplicate entry) into the `Response` the route means to return instead of throwing a custom `Error` subclass with a `status` field and catching it later.
- **Trusting `params`, query strings, or external payloads without a schema.** Anything that crosses a trust boundary should be parsed before it reaches business logic.