0

I'm making an application using the t3 stack: next, prisma, tRPC. I'm following along with a certain tutorial that uses Clerk for auth and I'm using Supabase Auth instead. In the file where I define my tRPC procedure (i.e. setting up createTRPCContext) I need to get access to session data in my tRPC context which I can then pass through into my tRPC router. The author of the tutorial does this with Clerk's getAuth, but it's unclear how to do this with supabase.

The docs recommend using await supabase.auth.getSession(); to get session data. But in order to create an instance of supabase I figured I can either use the provided hooks or createServerSupabaseClient method. Hooks won't work because it's not a React component/hook; createServerSupabaseClient won't work because I need to pass something into it. It also seems strange that I should instantiate another supabase instance.

What's the right way to get the user session data in my tRPC procedure?

crevulus
  • 1,658
  • 12
  • 42

1 Answers1

0

you need the context https://trpc.io/docs/context#inner-and-outer-context.

in trpc, you have inner context and outer context, so you can get the nextjs api context

// server/trpc.ts

// inner context
interface CreateInnerContextOptions extends Partial<CreateNextContextOptions> {
supabase: SupabaseClient | null;
}

// outer context
export async function createContextInner(opts?: CreateInnerContextOptions) {
    return {
        supabase: opts?.supabase as SupabaseClient<Database> ?? null,
    };
}

export async function createContext(opts: CreateNextContextOptions) {
    const supabase = createPagesServerClient<Database>(opts);
    const contextInner = await createContextInner({ supabase });
    return {
        ...contextInner,
        req: opts.req,
        res: opts.res,
    };
}
export type Context = inferAsyncReturnType<typeof createContextInner>;

//standard trpc declaration and passing context type 
const t = initTRPC.context<Context>().create()

and pass the createContext

// [trpc].ts
export default trpcNext.createNextApiHandler({
    router: appRouter,
    createContext
});

then you can consume the context like

// [trpc].ts
publicProcedure.input( ...).mutation(async({input, ctx}) => {
const supabase = ctx.supabase
...rest of the code