cucaracha
cucaracha3mo ago

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>
);
}
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 },
},
});
});
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 },
},
});
});
0 Replies
No replies yetBe the first to reply to this messageJoin