Part 11 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-11tag.
Part 10 ended with anyone able to create a user and nothing recording who did it. This part fixes both. POST /users needs a bearer token now, and the created event gets an actor_id.
The usual Node answer is a middleware that sets req.user. With Passport, @types/passport declares it as user?: User | undefined on every Express request, because the type can’t know whether the middleware ran on this route. Every handler then writes req.user! or checks again. I wanted the opposite: code that needs a user says so in its type, and a route that doesn’t authenticate can’t call it.
Tokens, stored hashed
Tokens live in Postgres, in a new migration:
CREATE TABLE api_tokens ( token_hash text PRIMARY KEY, user_id bigint NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT now());ALTER TABLE user_events ADD COLUMN actor_id bigint REFERENCES users (id)A Tokens service issues them and checks them. A token is 32 random bytes from node:crypto, and the table only ever sees its SHA-256. If the table leaks, nobody can log in with what’s in it. These are random tokens rather than passwords, so a fast hash is enough; bcrypt is for secrets a human picked.
verify: Effect.fn("Tokens.verify")( function* (token: Redacted.Redacted) { return yield* findByHash(hash(Redacted.value(token))).pipe( Effect.catchTag("NoSuchElementError", () => new Unauthorized()), ) }, Effect.catchTags({ SqlError: Effect.die, SchemaError: Effect.die }),),It’s part 9’s SqlSchema.findOne again, joining api_tokens to users and decoding the row with User. A missing row means a bad token. To get one, npm run -s token -- 1 prints a new token for Ada, once.
The contract half
The middleware has two halves, like the API in part 5. The declaration goes in a module the client can import:
// The user behind the bearer token. Only the Authorization middleware provides it.export class CurrentUser extends Context.Service<CurrentUser, User>()("CurrentUser") {}
export class Unauthorized extends Schema.TaggedError<Unauthorized>()( "Unauthorized", {}, { httpApiStatus: 401 },) {}
export class Authorization extends HttpApiMiddleware.Service<Authorization, { provides: CurrentUser}>()("Authorization", { security: { bearer: HttpApiSecurity.bearer }, error: Unauthorized,}) {}CurrentUser is an ordinary service whose value is a User. Authorization says three things: it reads a bearer token, it provides CurrentUser, and it can fail with Unauthorized, which is a 401 the same way part 6’s UserNotFound is a 404. HttpApiSecurity.bearer also lands in the OpenAPI spec as a bearer security scheme, and POST /users lists 401 next to its 201 and 400.
Then the endpoint opts in:
// Creating a user needs a bearer token. get stays public.HttpApiEndpoint.post("create", "/users", { payload: NewUser, success: User.pipe(HttpApiSchema.status(201)),}).middleware(Authorization),get stays public. .middleware() works on a group or the whole API too, as part 6 did with Validation.
The implementation half
// Look the token up, then run the endpoint with its user provided as CurrentUser.const AuthorizationLive = Layer.effect( Authorization, Effect.gen(function* () { const tokens = yield* Tokens return Authorization.of({ bearer: Effect.fn("Authorization.bearer")(function* (httpEffect, { credential }) { const user = yield* tokens.verify(credential) return yield* Effect.provideService(httpEffect, CurrentUser, user) }), }) }),).pipe(Layer.provide(Tokens.layer))The bearer key matches the key in security. Effect parses the Authorization header and hands over the token as a Redacted, so it prints as <redacted> in logs, like part 7’s database URL. httpEffect is the rest of the request: the payload decoding and the handler. The middleware runs it with CurrentUser provided, and if verify fails, it never runs.
AuthorizationLive goes next to ValidationLive in the group’s Layer.provide. Tokens.layer needs SqlClient, which part 9 already provides once, outside serve. main.ts is 61 non-blank lines (part 10: 46).
Asking for the user
Here’s the line the whole part is for. Users.create yields CurrentUser itself:
function* (input: NewUser) { // Yielding CurrentUser puts it in create's type: only a caller that has a user can run it. const actor = yield* CurrentUser const user = yield* insert(input) yield* sql`INSERT INTO user_events ${sql.insert({ user_id: user.id, type: "created", actor_id: actor.id })}`create now returns Effect<User, never, CurrentUser>. The handler didn’t change at all; it’s still users.create(payload), and it compiles because the endpoint’s middleware provides CurrentUser. I deleted .middleware(Authorization) from the endpoint to check, in src/part-11/types.ts:
error TS2375: Type 'Layer<Service<"open", "users">, never, Request<"Requires", CurrentUser>>' is not assignable to type 'Layer<Service<"open", "users">, never, never>' Type 'Request<"Requires", CurrentUser>' is not assignable to type 'never'.That’s the same per-request requirement part 8 ran into with Users. Make the same deletion in the real Api.ts and main.ts fails on its last line, with CurrentUser left in the requirements of the effect runMain gets. The same thing happens outside HTTP. A script that creates a user gets CurrentUser | Users in its requirements and has to provide someone, which is what the part 8 side files now do with Ada.
A middleware that checks the token and forgets to provide the user doesn’t compile either: Type 'CurrentUser' is not assignable to type 'Provided'.
What curl sees
POST /users, no header 401 {"_tag":"Unauthorized"}POST /users, Bearer nope 401 {"_tag":"Unauthorized"}POST /users, Basic <token> 401 {"_tag":"Unauthorized"}POST /users, Bearer <token> 201 {"id":"2","name":"Grace","email":"grace@example.com"}POST /users, bearer <token> 201 {"id":"3","name":"Linus","email":"linus@example.com"}GET /users/2, Bearer nope 200 {"id":"2","name":"Grace","email":"grace@example.com"}Both new events have actor_id 1, Ada. The lowercase bearer works because HTTP auth schemes are case-insensitive, and Effect’s parser follows RFC 9110 there. GET ignores the bad token because nothing on that endpoint reads it.
The client sends the token on every request with transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(token)), reading TOKEN with Config.Redacted. Run it with TOKEN=nope and it fails with the rebuilt Unauthorized class. Its type knows that too: catchTag("Unauthorized") compiles on create and fails on get.
Gotchas
- 401 beats 400. An unauthenticated POST with a blank name gets a 401, not part 6’s
BadRequest. Payload decoding happens insidehttpEffect, and the middleware never runs it. Same for broken JSON. I think that’s right: a stranger shouldn’t learn your validation rules. - A missing header isn’t a decode failure. Effect reads a missing or malformed
Authorizationheader as an emptyRedactedand calls your middleware anyway.1 Mine hashes the empty string and finds nothing, which costs one query. If yours checks a signature instead, make sure""fails. - No
WWW-Authenticateheader. RFC 6750 asks for one on a bearer 401. Effect 4.0.5 doesn’t add it, and curl and the Effect client didn’t care, so I left it out. - Tokens never expire. Revoking one means deleting its row. An
expires_atcolumn is a one-line migration when something needs it.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-11npm installdocker compose up -d --waitcp .env.example .envnpm startIn another terminal:
TOKEN=$(npm run -s token -- 1)curl -X POST localhost:3000/users -H "authorization: Bearer $TOKEN" \ -H 'content-type: application/json' -d '{"name":"Grace","email":"grace@example.com"}'A database from part 10 picks up migration 3 on the next start, and its old events keep a null actor_id. effect 4.0.6 is out, and the repo is still on 4.0.5.
Ada can create users now, and so can anyone holding one of her tokens. I’ve checked all of this with curl, by hand, which is starting to wear on me.
Next in the series: testing it with @effect/vitest.
- Part 12 — Testing handlers with @effect/vitest: Part 11's curl table becomes six tests. HttpApiTest calls the real handlers and middleware in process, with Users in memory and a fake Tokens: no port, no database.
Footnotes
-
securityDecodeinpackages/effect/src/http-api/HttpApiBuilder.tsateffect@4.0.5returnsRedacted.make(getAuthorizationCredential(...) ?? "")for theHttpscheme. The same file’smakeSecurityMiddlewareis what calls yourbearerfunction with the credential. ↩

