# Auth middleware and a CurrentUser service

- Published: 2026-11-18
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-11-auth-middleware-and-current-user/

> Part 11 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-11), and this part is the `part-11` tag.

[Part 10](/writing/effect-backend-10-transactions-and-scopes/) 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:

```sql title="src/migrations/0003_create_api_tokens.ts (excerpt)"
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.

```ts title="src/Tokens.ts (excerpt)"
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](/writing/effect-backend-5-httpapi-define-once/). The declaration goes in a module the client can import:

```ts title="src/Auth.ts"
// 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:

```ts title="src/Api.ts (excerpt)"
// 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

```ts title="src/main.ts (excerpt)"
// 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:

```ts title="src/Users.ts (excerpt)"
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`:

```text title="npm run check (src/part-11/types.ts without its @ts-expect-error, trimmed)"
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'`.

<Quiz
  question="You delete .middleware(Authorization) from the create endpoint. The handler still calls users.create(payload), and Users.create yields CurrentUser. What happens?"
  options={[
    {
      text: "Every POST /users answers 401",
      explanation:
        "Nothing on the endpoint checks a token any more, so nothing can answer 401. The compiler stops it before it runs.",
    },
    {
      text: "It doesn't compile: CurrentUser is left in the group's requirements",
      correct: true,
      explanation:
        'The middleware was the only thing providing CurrentUser. Without it the group\'s layer has Request<"Requires", CurrentUser> in its third type parameter.',
    },
    {
      text: "It runs, and the event gets a null actor_id",
      explanation:
        "Users.create can't run without a CurrentUser, and the type says so before anything runs.",
    },
  ]}
/>

## What curl sees

```text title="curl against npm start"
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 inside `httpEffect`, 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 `Authorization` header as an empty `Redacted` and calls your middleware anyway.[^decode] Mine hashes the empty string and finds nothing, which costs one query. If yours checks a signature instead, make sure `""` fails.
- **No `WWW-Authenticate` header.** 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_at` column is a one-line migration when something needs it.

**Quiz:** POST /users with no Authorization header and the body {"name":""}. What comes back?

- 400 BadRequest with the name issue
- 401 Unauthorized
- 500, because the header is missing

**Answer:** 401 Unauthorized — The middleware sees an empty token, the lookup fails, and httpEffect, which includes the payload decoding, never runs.

- Not "400 BadRequest with the name issue": That needs the payload decoded, and decoding happens inside the effect the middleware wraps. The middleware fails before it.
- Not "500, because the header is missing": A missing header becomes an empty Redacted credential, not an error. Your middleware decides what that means.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-11
npm install
docker compose up -d --wait
cp .env.example .env
npm start
```

In another terminal:

```sh
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`.

[^decode]: `securityDecode` in `packages/effect/src/http-api/HttpApiBuilder.ts` at [`effect@4.0.5`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/src/http-api/HttpApiBuilder.ts) returns `Redacted.make(getAuthorizationCredential(...) ?? "")` for the `Http` scheme. The same file's `makeSecurityMiddleware` is what calls your `bearer` function with the credential.

---

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