Skip to content

hono-agents agentsMiddleware TS error #112

Description

@Sillyvan

Hi there

i am using the hono-agents middleware and in my case i need access to the ctx inside the middleware so i did the following

const app = new Hono<{ Bindings: Env; Variables: { user: User | null; session: Session | null } }>();

app.use(
  '*',
  async (c, next) =>
    await agentsMiddleware({
      options: {
        onBeforeConnect: () => {
          if (!c.get('user')) return new Response('Unauthorized', { status: 401 });
        },
      },
      onError: (error) => {
        console.error(error);
      },
    })(c, next)
);

which works fine of course but it spits following typescript error now:

Argument of type 'Context<{ Bindings: Env; Variables: { user: { id: string; name: string; email: string; emailVerified: boolean; createdAt: Date; updatedAt: Date; image?: string | null | undefined; } | null; session: { ...; } | null; }; }, "*", {}>' is not assignable to parameter of type 'Context<Env, string, {}>'.
  Types of property 'set' are incompatible.
    Type 'Set<{ Bindings: Env; Variables: { user: { id: string; name: string; email: string; emailVerified: boolean; createdAt: Date; updatedAt: Date; image?: string | null | undefined; } | null; session: { ...; } | null; }; }>' is not assignable to type 'Set<Env>'.
      Type 'Env' is not assignable to type '{ Bindings: Env; Variables: { user: { id: string; name: string; email: string; emailVerified: boolean; createdAt: Date; updatedAt: Date; image?: string | null | undefined; } | null; session: { ...; } | null; }; }'.
        Types of property 'Bindings' are incompatible.
          Type 'object | undefined' is not assignable to type 'Env'.
            Type 'undefined' is not assignable to type 'Env'.ts(2345)

The following code makes the type error go away:

app.use(
  '*',
  createMiddleware(
    async (c, next) =>
      await agentsMiddleware({
        options: {
          onBeforeConnect: () => {
            if (!c.get('user')) return new Response('Unauthorized', { status: 401 });
          },
        },
        onError: (error) => {
          console.error(error);
        },
      })(c, next)
  )
);

Not sure if the types are fixable or if it should just be mentioned in the docs. either way would make sense i think

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions