Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tRPC How to encapsulate middleware?

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.

like image 614
manwingbb Avatar asked Sep 12 '25 14:09

manwingbb


1 Answers

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,
    },
  });
})
like image 98
Anass Avatar answered Sep 14 '25 03:09

Anass