Ayush GoyalA
tRPC3y ago
3 replies
Ayush Goyal

Passing objects to the next() function of the middle ware

// -------------------------------------------------
// @filename: context.ts
// -------------------------------------------------
import type { inferAsyncReturnType } from '@trpc/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import { getSession } from 'next-auth/react';
 
/**
 * Creates context for an incoming request
 * @link https://trpc.io/docs/context
 */
export async function createContext(opts: CreateNextContextOptions) {
  const session = await getSession({ req: opts.req });
 
  return {
    session,
  };
}
 
export type Context = inferAsyncReturnType<typeof createContext>;
 
// -------------------------------------------------
// @filename: trpc.ts
// -------------------------------------------------
import { initTRPC, TRPCError } from '@trpc/server';
import { Context } from './context';
 
const t = initTRPC.context<Context>().create();
 
const isAuthed = t.middleware(({ next, ctx }) => {
  if (!ctx.session?.user?.email) {
    throw new TRPCError({
      code: 'UNAUTHORIZED',
    });
  }
  return next({
    ctx: {
      // Infers the `session` as non-nullable
      session: ctx.session,
    },
  });
});
 
export const middleware = t.middleware;
export const router = t.router;
 
/**
 * Unprotected procedure
 */
export const publicProcedure = t.procedure;
 
/**
 * Protected procedure
 */
export const protectedProcedure = t.procedure.use(isAuthed);


i never knew if one can pass arguments to the next() function , my doubt is why are we passing them and how do we use them
Was this page helpful?