Part 5 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the
part-5tag.
Part 4’s src/main.ts had 49 non-blank lines. About half of them were me telling each route which schema to decode with and what to do when decoding failed. The schemas lived in one file, and the routes that used them lived in another, and nothing checked that a client calling /users agreed with either.
This part moves both routes into an HttpApi. src/main.ts drops to 22, and I get an OpenAPI document and a typed client without writing either. One thing gets worse, though, and the document turns out to promise something the server doesn’t do.
The contract
An HttpApi is a value. It holds groups, and a group holds endpoints. Each endpoint has a name, a method, a path, and schemas for whatever it reads and returns.1 Here are part 4’s two user routes as a contract:
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api"import { NewUser, User, UserParams } from "./User.ts"
export const UsersGroup = HttpApiGroup.make("users").add( HttpApiEndpoint.get("get", "/users/:id", { params: UserParams, success: User, }), HttpApiEndpoint.post("create", "/users", { payload: NewUser, success: User.pipe(HttpApiSchema.status(201)), }),)
export const Api = HttpApi.make("api").add(UsersGroup)UserParams and NewUser are part 4’s schemas, unchanged. The only new one is User, the response. Until now, User was a TypeScript interface in Users.ts, and an interface can’t encode anything. So User.ts gained a schema, and Users.ts now takes its User type from it:
export const User = Schema.Struct({ id: Schema.String, name: Schema.String, email: Schema.optionalKey(Schema.String),}).annotate({ identifier: "User" })export type User = typeof User.TypeThe status code is part of the schema. HttpApiSchema.status(201) is how create says it answers 201, and an endpoint with no success at all answers 204.
There are no handlers in Api.ts and no Node imports. That matters later, because the client imports this file.
One thing to know before you build on it. Every export of effect/http-api is marked @stability unstable in 4.0.5, which means breaking changes are allowed in minor releases. The path lost its unstable/ segment in 4.0, but Effect’s migration guide says moving these modules “does not stabilize their APIs”.2 That’s why part 1 pinned effect to exactly 4.0.5.
The server
Here’s all of src/main.ts now:
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"import { Effect, Layer } from "effect"import { HttpRouter, HttpServerResponse } from "effect/http"import { HttpApiBuilder, HttpApiScalar } from "effect/http-api"import { createServer } from "node:http"import { Api } from "./Api.ts"import { getUser } from "./getUser.ts"import { Users } from "./Users.ts"
const UsersLive = HttpApiBuilder.group(Api, "users", (handlers) => handlers .handle("get", ({ params }) => getUser(params.id).pipe(Effect.orDie)) .handle("create", ({ payload }) => Users.use((users) => users.create(payload))),)
const Health = HttpRouter.add("GET", "/health", HttpServerResponse.text("ok"))
const ApiRoutes = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe( Layer.provide(UsersLive),)
const Server = HttpRouter.serve(Layer.mergeAll(Health, ApiRoutes, HttpApiScalar.layer(Api))).pipe( Layer.provide(Users.layer), Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),)
Layer.launch(Server).pipe(NodeRuntime.runMain)HttpApiBuilder.group takes the contract and a group name, and you hand it one function per endpoint. Each handler gets its input already decoded: params.id is a UserId and payload is a NewUser. There’s no schemaPathParams call and no catchTag. Decoding happens before the handler runs, and a handler only runs if it worked.
HttpApiBuilder.layer turns the whole contract into routes on part 3’s router. /health is still a plain HttpRouter.add next to it, so you can move routes over one at a time. The bottom four lines are the same as in part 3.
The Effect.orDie on get is a stopgap. getUser can fail with UserNotFound, and the contract doesn’t say get can fail. orDie turns the failure into a defect, which is a 500, the same as in part 4. The last section shows what happens without it.
GET /health 200 okGET /users/1 200 {"id":"1","name":"Ada"}GET /users/abc 400 (empty body)GET /users/2 500POST {"name":" Grace ","email":"grace@example.com","isAdmin":true} 201 {"id":"2","name":"Grace","email":"grace@example.com"}POST {"name":" ","email":"nope"} 400 (empty body)POST {"name": 400 (empty body)POST without content-type: application/json 415 Unsupported content-type: application/x-www-form-urlencodedThis is the thing that got worse. Part 4’s 400s listed every bad field. These are empty. The log still knows why, but the client doesn’t:
INFO (#21) http.span=0ms: HttpApiSchemaError: Payload { [cause]: SchemaError: Expected a value with a length of at least 1 at ["name"]}And it only names name. The email was bad too, but HttpApi decodes without part 4’s errors: "all", so it stops at the first problem. Part 6 gives the 400 its body back.
The 415 is new as well. Part 4’s schemaBodyJson parsed a body sent with curl’s default form content type. HttpApi turns it away.
The client
The same contract gives you a client. It’s typed from the schemas, and it decodes responses with them too:
import { Effect } from "effect"import { FetchHttpClient } from "effect/http"import { HttpApiClient } from "effect/http-api"import { Api } from "./Api.ts"import { UserId } from "./User.ts"
const program = Effect.gen(function* () { const client = yield* HttpApiClient.make(Api, { baseUrl: "http://localhost:3000" }) const created = yield* client.users.create({ payload: { name: "Grace", email: "grace@example.com" }, }) const found = yield* client.users.get({ params: { id: UserId.make(created.id) } }) console.log({ created, found }) yield* client.users.create({ payload: { name: "", email: "nobody@example.com" } })})
program.pipe(Effect.provide(FetchHttpClient.layer), Effect.runPromise).catch(console.error){ created: { id: '4', name: 'Grace', email: 'grace@example.com' }, found: { id: '4', name: 'Grace', email: 'grace@example.com' }}{ _tag: 'SchemaError', message: 'Expected a value with a length of at least 1\n at ["name"]'}The second create never left the process. The server log shows the POST and the GET, and nothing after them. The client encodes the payload with NewUser before sending it, so an empty name fails on the caller’s side.
My first version passed created.id straight to get, and tsc refused: Type 'string' is not assignable to type 'string & Brand<"UserId">'. It was right. The User schema says id is a string, and UserParams wants a UserId, so the contract had caught two of my own schemas disagreeing. UserId.make checks the pattern and adds the brand.
The document
openapiPath: "/openapi.json" serves an OpenAPI 3.1 document built from the contract, and HttpApiScalar.layer(Api) serves a docs page for it at /docs. Swagger UI is the same idea with HttpApiSwagger.layer. If you want the JSON without a server, OpenApi.fromApi(Api) returns it.
"/users": { "post": { "operationId": "users.create", "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User_1" } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string" }, "email": { "type": "string" } }, "required": ["name", "email"], "additionalProperties": false } } } } }}Everything reads from one value, so change the contract and all three move with it. Not every change is a compile error, though. Here are four edits I made to src/Api.ts and src/User.ts, one at a time:
HttpApiEndpoint.delete("remove", "/users/:id", { params: UserParams })
- Server
- tsc fails at HttpApiBuilder.group: not assignable to type "Endpoint not handled: remove".
- Client
- Compiles. client.users.remove exists now, and nothing calls it yet.
- OpenAPI
- DELETE /users/{id} appears, documented as a 204, because the endpoint has no success schema.
HttpApiEndpoint.get("get", "/users/:id", …) removed
- Server
- tsc fails in src/main.ts: Argument of type '"get"' is not assignable to parameter of type '"create"'.
- Client
- tsc fails in src/client.ts: Property 'get' does not exist.
- OpenAPI
- /users/{id} is gone from the document.
email: Schema.optionalKey(…)
- Server
- Compiles. POST {"name":"Grace"} now answers 201 with no email.
- Client
- Compiles. src/client.ts still sends an email, which is still allowed.
- OpenAPI
- email leaves the body's "required" list.
success: User
- Server
- Compiles. POST /users answers 200 instead of 201.
- Client
- Compiles, and still decodes the created user.
- OpenAPI
- POST /users is documented as 200.
Two of the four compile without a word. Dropping status(201) changes what every caller gets back, and tsc has nothing to say about it, because nothing in the types depends on the status code. The document is the only place the change shows.
The gotchas, and when not to bother
Look at that request body again. src/part-5/openapi.ts prints the parts of the document that don’t match the server:
GET /users/{id} responses: [ '200' ]POST /users responses: [ '201' ]POST /users body: {"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"}},"required":["name","email"],"additionalProperties":false}components: [ 'User_1', 'User' ]Int id pattern: ^[+-]?\d*\.?\d+(?:[Ee][+-]?\d+)?$pattern matches "1.5": true- The spec says
additionalProperties: false, but the server drops extras. TheisAdminPOST above was a 201. The document forbids extra keys, and the server accepts them and throws them away. - There are no 400s in the spec. Every endpoint here can answer 400, and the document lists only the success status.
- The checks don’t make it into the spec. The id is documented as a plain string, without part 4’s pattern, and
namehas no minimum length. - An
Intparam’s pattern matches1.5. Part 4 kept ids as strings, so this one isn’t in the server. But if you declare a param asSchema.Int, the documented pattern accepts1.5, and the server rejects it with a 400. User_1is the same schema asUser.status(201)makes a copy, and the document has both components.- The client checks payloads against the decoded type, as in the second quiz. A value the server would happily clean up can fail before it’s sent.
- Any import loads about 5 MB of docs UI. In 4.0.5, importing anything from
effect/http-apievaluates the bundled Scalar and Swagger assets, whether you serve/docsor not. On my machine,effectpluseffect/httpwas 104 MB of memory, and addingeffect/http-apimade it 153 MB. The fix is on Effect’smainbranch and hasn’t been released.3 - Sharing the contract with a browser isn’t free. When I bundled an
HttpApiClientfor a contract like this one with esbuild for the browser, it came to 118 KB gzipped. None of the docs UI ended up in it.
When not to bother: a route nobody else calls. If the only caller is your own code in another service, that’s a question for part 16, which compares this with Effect’s RPC.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-5npm installnpm startOpen localhost:3000/docs for the Scalar page, and run node src/client.ts in another terminal. src/part-5/ has the OpenAPI script above and the type errors below.
What the types tell you
src/part-5/types.ts is type-check only, with an @ts-expect-error on each line that shouldn’t compile. Here’s npm run check without them:
error TS2322: Type 'Handlers<…, "get">' is not assignable to type '"Endpoint not handled: create"'.error TS2375: Type 'Effect<{ id: string & Brand<"UserId">; fullName: string; }, never, never>' is not assignable to type 'Effect<{ readonly id: string; readonly name: string; readonly email?: string; } | HttpServerResponse, never, never>' Property 'name' is missing in type '{ id: string & Brand<"UserId">; fullName: string; }'error TS2322: Type 'string' is not assignable to type 'string & Brand<"UserId">'.error TS2339: Property 'remove' does not exist on type '{ readonly get: …; readonly create: … }'.error TS2375: Type 'Effect<{ … }, UserNotFound, Users>' is not assignable to type 'Effect<{ … } | HttpServerResponse, never, Users>' Type 'UserNotFound' is not assignable to type 'never'.In order: a group that handles get and forgets create, a handler that returns fullName, a client call with a plain string id, and a client call to an endpoint that doesn’t exist.
The last one is get without the Effect.orDie. The handler’s error slot has to be never, because the contract doesn’t declare any errors for get, and UserNotFound isn’t never. The contract has no way to say “this endpoint can answer 404”, so I made the error a defect to get it past tsc. Part 6 lets get declare UserNotFound with its own status code, and /users/2 finally becomes a 404.
Next in the series: typed errors become status codes.
- Part 6 — Typed errors become status codes: UserNotFound carries its own 404, the client catches it by name, and every bad request gets a 400 that says what was wrong.
Footnotes
-
HTTPAPI.mdat theeffect@4.0.5tag is the HttpApi guide. The v4 docs site has no HttpApi page yet. ↩ -
MIGRATION.mdlistshttp-apiamong the modules that moved out ofunstable/, and says the move doesn’t stabilize them. The@stability unstabletags are ineffect/dist/http-api/index.d.ts. ↩ -
The unreleased changeset is
http-api-lazy-docs-assets.md: “Importing the module no longer evaluates about 5 MB of embedded JavaScript and CSS.” ↩

