cucarachaC
tRPC16mo ago
4 replies
cucaracha

Auth in context is initially null leading to TRPCClientError: UNAUTHORIZED

im trying to get some images in my server component using a protected procedure
import { api } from '@/app/_trpc/server';
import Images from '@/components/images';

export default async function Home() {
  void api.main.getImages.prefetch();

  return (
    <main className="container flex flex-col pt-8">
      <Images />
    </main>
  );
}


problem is that the session is initially null (using nextauth5) in my context which leads to a TRPCClientError: UNAUTHORIZED. then another call is made and the session exists

export const createTRPCContext = async (opts: { headers: Headers }) => {
  const session = await auth();

  return {
    db,
    session,
    ...opts,
  };
};

export const protectedProcedure = t.procedure
  .use(timingMiddleware)
  .use(({ ctx, next }) => {
    if (!ctx.session || !ctx.session.user) {
      throw new TRPCError({ code: 'UNAUTHORIZED' });
    }
    return next({
      ctx: {
        // infers the `session` as non-nullable
        session: { ...ctx.session, user: ctx.session.user },
      },
    });
  });
Was this page helpful?