I am trying to put middleware into its own function but I am struggling to get proper typescript typing on it.
At the moment I am typing the middleware as follows, but this isn't ideal because the type information of context and metadata are lost after returning from the middleware.
Inside the middleware
import { MiddlewareFunction } from "@trpc/server/dist/declarations/src/internals/middlewares";
import { TRPCError } from "@trpc/server";
export const authMiddleware : MiddlewareFunction<any, any, any> = async ({ ctx, next, path, rawInput, type, meta }) => {
  if (!meta?.auth)
    return next();
  // some random logic
  return next();
}
And this is how I want to consume it
createRouter()
  .middleware(authMiddleware)
  .mutation('', {
    meta: {
      auth: "user",
      appCheck: true
    },
    input: object({
      workshopId: idSchema,
    }),
    resolve: async ({ input, ctx, type }) => {
    // Here ctx has been widened to any
    // ...
Thank you in advance.
const t = initTRPC.context<Context>().create();
const middleware = t.middleware;
const authMiddleware = t.middleware(({ next, ctx }) => {
  if (!ctx.session) {
    throw new TRPCError({
      code: "UNAUTHORIZED",
    });
  }
  return next({
    ctx: {
      // Infers the `session` as non-nullable
      session: ctx.session,
    },
  });
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With