Using services within an `HttpApiMiddleware` can be tricky due to type constraints. The error you...

Hello, is it possible to use any service from a HttpApiMiddleware?

I have this setup:

My Authorization middleware

export class Authorization extends HttpApiMiddleware.Tag<Authorization>()(
  'Authorization',
  {
    failure: Schema.Union(
      InvalidToken,
      Unauthorized,
      Forbidden,
      InternalServerError,
    ),
    provides: ZitadelToken,
    security: {
      bearer: HttpApiSecurity.bearer,
    },
  },
) {}

export class ZitadelToken extends Context.Tag('ZitadelToken')<
  ZitadelToken,
  jose.JWTVerifyResult & jose.ResolvedKey
>() {}


provides ZitadelToken.

I wish to use that within my ProfileRequired middleware:

export const BackendUserProfile = Schema.Struct({
  id: Schema.UUID,
  username: Schema.String,
});

export class CurrentProfile extends Context.Tag('Profile')<
  CurrentProfile,
  {
    profile: typeof BackendUserProfile.Type;
  }
>() {}

export class ProfileRequired extends HttpApiMiddleware.Tag<ProfileRequired>()('ProfileRequired',
{
 failure: Schema.Union(Forbidden, InternalServerError),
 provides: CurrentProfile,
},
) {}



which uses UserService to get the user profile from a database: (the code below works as long as I don't yield* the services (ZitadelToken & UserService), but once I do it tells me

Type 'Effect<{ profile: { id: string; username: string; }; }, never, ZitadelToken | UserService>' is not assignable to type 'Effect<{ profile: { readonly id: string; readonly username: string; }; }, Forbidden | InternalServerError, Provided>' with 'exactOptionalPropertyTypes: true'
Type 'ZitadelToken | UserService' is not assignable to type 'Provided'.


export const ProfileRequiredLive = Layer.effect(
 ProfileRequired,
 Effect.gen(function* () {
  return Effect.gen(function* () {
   const token = yield* ZitadelToken;
   const userService = yield* UserService;
   return {
    profile: {
     id: 'test',
     username: 'test',
    },
   };
  });
 }),
);


does anyone know a fix / better way?
Was this page helpful?