# Schema at the boundary

- Published: 2026-11-11
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-4-schema-at-the-boundary/

> Part 4 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-4), and this part is the `part-4` tag.

One request with `{"name": 42}` took my server down. Not the request, the server. Every other user's request went with it.

[Part 3](/writing/effect-backend-3-a-node-server-in-20-lines/) ended with `/users/:id` accepting any string. This part puts a Schema in front of it, adds `POST /users` with a JSON body, and makes bad input a 400 that tells the client what was wrong.

## The plain version

Here's `POST /users` in plain `node:http`. It reads the body, parses it, and trusts it:

```ts title="src/part-4/plain.ts"
import { createServer } from "node:http"

const users = new Map([["1", { id: "1", name: "Ada", email: "ada@example.com" }]])

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/users") return res.writeHead(404).end()
  let raw = ""
  for await (const chunk of req) raw += chunk
  const body = JSON.parse(raw) as { name: string; email: string }
  const user = { id: String(users.size + 1), name: body.name.trim(), email: body.email }
  users.set(user.id, user)
  res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify(user))
}).listen(3000)
```

The `as` is the problem. It's a promise to TypeScript that nobody checks at runtime. Send a good body, then a bad one, then a good one again:

```text title="curl, three POSTs to /users"
{"id":"2","name":"Grace","email":"grace@example.com"}  201
curl: exit 52 (empty reply from server)
curl: exit 7  (couldn't connect)
```

```text title="node src/part-4/plain.ts"
TypeError: body.name.trim is not a function
    at Server.<anonymous> (src/part-4/plain.ts:12:62)

Node.js v24.16.0
exit 1
```

The throw happens inside an async handler, the process exits with code 1, and the third request has nothing to connect to. As far as I can tell, nothing catches the rejected promise, and Node treats that as fatal.

The Effect server from part 3 doesn't crash, but it doesn't check anything either. `GET /users/abc` goes straight to `getUser("abc")`, which fails with `UserNotFound`, which is a 500. The client sent a bad id, and the server said it was the server's fault.

## A schema is a parser with a type attached

In Effect 4, `Schema` lives in the core package: `import { Schema } from "effect"`.[^schema] A schema has two sides. The `Encoded` side is what arrives on the wire, and the `Type` side is what your code gets after decoding. For a path param, the encoded side is always a string.

Here are the two schemas this part needs, in their own module so later parts can import them:

```ts title="src/User.ts"
import { Schema } from "effect"

export const UserId = Schema.String.check(
  Schema.isPattern(/^[1-9][0-9]*$/, { message: "Expected a positive integer" }),
).pipe(Schema.brand("UserId"))
export type UserId = typeof UserId.Type

export const UserParams = Schema.Struct({ id: UserId })

export const NewUser = Schema.Struct({
  name: Schema.Trim.check(Schema.isMinLength(1), Schema.isMaxLength(100)),
  email: Schema.Trim.check(
    Schema.isPattern(/^[^@\s]+@[^@\s]+$/, { message: "Expected an email address" }),
  ),
})
export type NewUser = typeof NewUser.Type
```

`.check(...)` adds filters, and in v4 they're all `is*` functions. `Schema.Trim` decodes a string by trimming it, so `"  Grace  "` becomes `"Grace"` before the length check runs. `Schema.brand("UserId")` changes only the type: a decoded id is a `string & Brand<"UserId">`, and a plain string isn't one. The brand adds no runtime check.[^brand]

The id stays a string because the users map is keyed by strings, and every earlier part's code calls `find("1")`. If you reach for `Schema.FiniteFromString` here, which turns the string into a number, the gotchas section shows what gets through.

`Users` also grew a `create(input: NewUser)` method, an `Effect.fn("Users.create")` that gives the user the next id and stores it.

**Quiz:** NewUser declares only name and email. A client posts {name, email, isAdmin: true}. What does users.create receive?

- All three keys, isAdmin included
- Only name and email
- A SchemaError for the extra key

**Answer:** Only name and email — Unknown keys are ignored by default and left out of the decoded value. You get no error, and nothing reaches create.

- Not "All three keys, isAdmin included": Decoding builds a new object from the keys the schema declares.
- Not "A SchemaError for the extra key": Only if you ask for it with onExcessProperty: "error".

## Decode at the edge of the route

`effect/http` has one decoding helper for each part of the request. All of them fail with a `SchemaError` when the input doesn't match:

| Request part          | Helper                                         |
| --------------------- | ---------------------------------------------- |
| Path params           | `HttpRouter.schemaPathParams(schema)`          |
| Query string          | `HttpServerRequest.schemaSearchParams(schema)` |
| Path and query merged | `HttpRouter.schemaParams(schema)`              |
| Headers               | `HttpServerRequest.schemaHeaders(schema)`      |
| JSON body             | `HttpServerRequest.schemaBodyJson(schema)`     |

They're marked `@stability unstable` in their JSDoc, like the rest of `effect/http`, which is why part 1 pinned the version. There's also `HttpRouter.schemaJson`, which decodes the whole request in one schema. I prefer the separate helpers, because each one says which part of the request it's reading.

Here are the two user routes in `src/main.ts`. `GET` swaps part 3's `HttpRouter.params` for `schemaPathParams`, and `POST` is new:

```ts title="src/main.ts (excerpt)"
const GetUser = HttpRouter.add(
  "GET",
  "/users/:id",
  Effect.fn("UsersHttp.get")(
    function* () {
      const { id } = yield* HttpRouter.schemaPathParams(UserParams)
      const user = yield* getUser(id)
      return HttpServerResponse.jsonUnsafe(user)
    },
    Effect.catchTag("SchemaError", invalid),
  ),
)

const CreateUser = HttpRouter.add(
  "POST",
  "/users",
  Effect.fn("UsersHttp.create")(
    function* () {
      const input = yield* HttpServerRequest.schemaBodyJson(NewUser, { errors: "all" })
      const users = yield* Users
      const user = yield* users.create(input)
      return HttpServerResponse.jsonUnsafe(user, { status: 201 })
    },
    Effect.catchTags({ SchemaError: invalid, HttpServerError: notJson }),
  ),
)
```

Below the `yield*` line, `id` is a `UserId` and `input` is a `NewUser`. The handler never sees the raw string. The recovery goes in `Effect.fn`'s extra argument, as part 2 recommended, so it runs inside the span. `invalid` and `notJson` are the next section.

## What happens if you do nothing

Before writing them, I deleted both `catch` lines and sent the same bad requests. Nothing crashed:

```text title="curl, no catchTag"
GET  /users/abc                     400 (empty body)
POST {"name":"   ","email":"nope"}  400 (empty body)
POST {"name":                       400 (empty body)
```

```text title="npm start (trimmed)"
INFO (#14) http.span=1ms: SchemaError: Expected a positive integer
  at ["id"]
INFO (#23) http.span=0ms: SchemaError: Expected a value with a length of at least 1
  at ["name"]
Expected an email address
  at ["email"]
INFO (#29) http.span=1ms: HttpServerError: RequestParseError (POST /users)
  [cause]: SyntaxError: Unexpected end of JSON input
```

The router knows about `SchemaError`. When one reaches it, it answers 400 instead of 500.[^respondable] Broken JSON isn't a `SchemaError`, though. It fails earlier, as an `HttpServerError` with the reason `RequestParseError`, and that's a 400 too.

So doing nothing already beats the plain server. But the log knows exactly what was wrong, and the client gets an empty body.

## Make the 400 say why

`SchemaError` is a tagged error with an `issue` field, so [`catchTag`](/writing/learning-effect-6-catch-one-error-not-the-world/) can catch it like any other. Effect ships a formatter that turns the issue into the Standard Schema shape, a list of `{ path, message }`:[^formatter]

```ts title="src/main.ts (excerpt)"
const formatIssues = SchemaIssue.makeFormatterStandardSchemaV1()

const invalid = (error: Schema.SchemaError) =>
  HttpServerResponse.json(
    { error: "BadRequest", issues: formatIssues(error.issue).issues },
    { status: 400 },
  )

const notJson = () =>
  HttpServerResponse.json(
    { error: "BadRequest", issues: [{ path: [], message: "Body is not valid JSON" }] },
    { status: 400 },
  )
```

Standard Schema is a format several validation libraries share, so a client may already know how to read it. The messages never include the rejected value. Schema leaves inputs out of messages unless you pass `reportInput: true`, which is the safe default when the input might be a password. `GET` only catches `SchemaError`, because that's the only decoding error it can get. `POST` uses `catchTags` for both. Here's the server answering:

```text title="curl against npm start"
GET  /users/1      200 {"id":"1","name":"Ada"}
GET  /users/abc    400 {"error":"BadRequest","issues":[{"path":["id"],"message":"Expected a positive integer"}]}
POST {"name":"  Grace  ","email":"grace@example.com","isAdmin":true}
                   201 {"id":"2","name":"Grace","email":"grace@example.com"}
POST {"name":"   ","email":"nope"}
                   400 {"error":"BadRequest","issues":[{"path":["name"],"message":"Expected a value with a length of at least 1"},{"path":["email"],"message":"Expected an email address"}]}
POST {"name":42}   400 {"error":"BadRequest","issues":[{"path":["name"],"message":"Expected string"},{"path":["email"],"message":"Missing key"}]}
POST {"name":      400 {"error":"BadRequest","issues":[{"path":[],"message":"Body is not valid JSON"}]}
POST []            400 {"error":"BadRequest","issues":[{"path":[],"message":"Expected object"}]}
```

Grace's name came back trimmed, and `isAdmin` is gone. The body that crashed the plain server is now a 400 naming both fields.

Both fields, because of `{ errors: "all" }`. By default decoding stops at the first failure, and that POST would only report `name`. For a form you want every field at once. For a single path param, the first error is all there is.

Here's what changed for the path param, request by request:

**The same path param through the part 3 and part 4 servers.**

| `/users/…` | Part 3 | Part 4 | Why |
| --- | --- | --- | --- |
| `1` | 200 {"id":"1","name":"Ada"} | 200 {"id":"1","name":"Ada"} | A real id. Both servers find Ada. |
| `abc` | 500, logged as UserNotFound: user abc not found | 400 [id] Expected a positive integer | Part 3 looked up "abc", found nobody, and blamed itself. Part 4 never calls getUser. |
| `0x1` | 500, logged as UserNotFound: user 0x1 not found | 400 [id] Expected a positive integer | Number("0x1") is 1. The pattern doesn't go through Number(), so it doesn't read hex. |
| `01` | 500, logged as UserNotFound: user 01 not found | 400 [id] Expected a positive integer | A leading zero is a different string from "1", so the pattern refuses it instead of guessing. |
| `%20` | 500, logged as UserNotFound: user   not found | 400 [id] Expected a positive integer | The router decodes %20 to a space before the schema sees it. |
| `2` | 500, logged as UserNotFound: user 2 not found | 500, logged as UserNotFound: user 2 not found | A valid id that nobody has. Schema can't help here. Part 6 turns this one into a 404. |

`/users/2` is still a 500. The id is valid and nobody has it, which Schema can't know. Part 6 turns that into a 404.

## What the types tell you

`src/part-4/types.ts` is type-check only, with an `@ts-expect-error` on each line that shouldn't compile. Here's what `npm run check` says without them:

```text title="npm run check (without the expect-error lines, trimmed)"
error TS2345: Argument of type 'Struct<{ readonly id: Number; }>' is not assignable to parameter of type 'ConstraintCodec<{ readonly id: number; }, Readonly<Record<string, string | undefined>>, never, unknown>'.
  Types of property '"Encoded"' are incompatible.
    Type '{ readonly id: number; }' is not assignable to type 'Readonly<Record<string, string | undefined>>'.
error TS2322: Type 'string' is not assignable to type 'string & Brand<"UserId">'.
```

The first error is `schemaPathParams(Schema.Struct({ id: Schema.Number }))`. A path param is a string, so the helper only takes a schema whose encoded side is strings. You can't skip saying how the string becomes something else. The second is `{ id: "1" }` typed as `UserParams`. A `UserId` only comes out of decoding.

The third thing is in the error channel. `schemaBodyJson(NewUser)` fails with `HttpServerError | SchemaError`, which is why `catchTag("SchemaError")` alone would have missed broken JSON.

**Quiz:** Say UserId were Schema.FiniteFromString.check(Schema.isInt()). What does GET /users/%20 decode to?

- A SchemaError, because a space isn't a number
- 0
- NaN

**Answer:** 0 — The router decodes %20 to a space, and Number(" ") is 0. 0 is a finite integer, so it passes.

- Not "A SchemaError, because a space isn't a number": FiniteFromString uses JavaScript's Number() rules, and those don't reject a space.
- Not "NaN": FiniteFromString rejects NaN. NumberFromString is the one that lets it through.

## The gotchas, and when not to bother

`src/part-4/gotchas.ts` runs each one:

```text title="node src/part-4/gotchas.ts (trimmed)"
FiniteFromString ""                  Success(0)
FiniteFromString " "                 Success(0)
FiniteFromString "0x10"              Success(16)
FiniteFromString "1e2"               Success(100)
NumberFromString "abc"               Success(NaN)
Date "2027-01-19"                    Failure(… Expected a valid Date)
DateFromString "2027-01-19"          Success(2027-01-19T00:00:00.000Z)
NewUser with isAdmin                 Success({"name":"Grace","email":"grace@example.com"})
NewUser, onExcessProperty: error     Failure(… Expected no excess property at ["isAdmin"])
```

- **`FiniteFromString` follows `Number()`.** An empty string and a space are both 0, `0x10` is 16 and `1e2` is 100. That's why `UserId` is a pattern on a string. If you want a number, add `isGreaterThan(0)` at least, and know that hex still gets through.
- **`NumberFromString("abc")` succeeds with `NaN`.** Never use it for an id.
- **Extra keys are dropped without a word.** That's good against mass assignment, since `isAdmin` never reaches `create`. If you'd rather tell the client, pass `{ onExcessProperty: "error" }`.
- **`Schema.Date` no longer parses strings.** In v4 it's the old `DateFromSelf`, an actual `Date` object. For an ISO string in JSON, use `Schema.DateFromString`. Code written for v3 still compiles and rejects every date.[^migration]
- **`Schema.Number` in `schemaPathParams` is a compile error**, as above. Use a `...FromString` schema or a string with a check.

When not to bother: inside your own code. Decode once at the edge, where `unknown` comes in, and pass the decoded value on. `getUser` takes a `string` and doesn't need to decode it again. The same schemas can decode environment variables too, which part 7 gets to.

What I don't like is the repetition. Every route has a `schema*` call and a `catchTag` that builds the same 400, and the schemas live apart from the routes that use them. Part 5 declares each endpoint's schemas once, and part 6 lets an error pick its own status code, which retires `invalid` and `notJson`.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-4
npm install
npm start
```

Then, in another terminal:

```sh
curl localhost:3000/users/abc
curl -H 'content-type: application/json' \
  --data '{"name":"  you  ","email":"you@example.com"}' localhost:3000/users
```

`src/part-4/` has the plain server that crashes, the type errors above, and the gotchas script.

Next in the series: HttpApi, where each endpoint's schemas are declared once.

[^schema]: [`SCHEMA.md`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/SCHEMA.md) at the `effect@4.0.5` tag is the v4 Schema guide. It covers unexpected keys, `errors: "all"`, `reportInput` and the formatters. There's also an `effect/schema` subpath, but it holds compilers and `Model`, not the `Schema` you validate with.

[^brand]: `SCHEMA.md`, "Branding": a brand "does not add runtime validation".

[^respondable]: [`HttpServerRespondable.ts`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/src/http/HttpServerRespondable.ts) at the `effect@4.0.5` tag: "schema errors become `400` responses". The response it builds has no body.

[^formatter]: `SchemaIssue.makeFormatterStandardSchemaV1()` returns `{ issues: { message, path }[] }`. See "StandardSchemaV1 formatter" in `SCHEMA.md`.

[^migration]: [`migration/schema.md`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/migration/schema.md) at the `effect@4.0.5` tag, "Date encoded contract". The same file has the v3 to v4 rename table, if you're reading older Schema posts: `decodeUnknown` is now `decodeUnknownEffect`, `Literal("a", "b")` is `Literals(["a", "b"])`, and filters are `is*` functions passed to `.check`.

- **Part 5 — HttpApi: define the API once**: The two user routes become one HttpApi contract, and the server, a typed client and an OpenAPI document all come from it.
