tRPC clerk auth context not working on Server side HTTP requests with NextJS app dir

I have setup tRPC as per the https://github.com/trpc/examples-next-app-dir/ but the server side http request do not have the auth context that I am passing in through clerk's getAuth()... I have done a bit of investigating and found the req I am passing to the getAuth does not have cookies in it but when I use client side http req it works as intended. I am wondering if this is intended behaviour or if its me setting things up wrong. My tRPC Context
import { getAuth } from '@clerk/nextjs/server';
import type { inferAsyncReturnType } from '@trpc/server';
import type { SignedInAuthObject, SignedOutAuthObject } from '@clerk/nextjs/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import db from '@/lib/db/drizzle-db';

type CreateContextOptions = {
auth: SignedInAuthObject | SignedOutAuthObject;
};

export const createContextInner = (opts: CreateContextOptions) => {
return {
auth: opts.auth,
db,
};
};

export const createContext = (opts: CreateNextContextOptions) => {
const req = opts.req;
const auth = getAuth(req);
console.log('auth', req, auth);
return createContextInner({
auth,
});
};

export type Context = inferAsyncReturnType<typeof createContext>;
import { getAuth } from '@clerk/nextjs/server';
import type { inferAsyncReturnType } from '@trpc/server';
import type { SignedInAuthObject, SignedOutAuthObject } from '@clerk/nextjs/server';
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
import db from '@/lib/db/drizzle-db';

type CreateContextOptions = {
auth: SignedInAuthObject | SignedOutAuthObject;
};

export const createContextInner = (opts: CreateContextOptions) => {
return {
auth: opts.auth,
db,
};
};

export const createContext = (opts: CreateNextContextOptions) => {
const req = opts.req;
const auth = getAuth(req);
console.log('auth', req, auth);
return createContextInner({
auth,
});
};

export type Context = inferAsyncReturnType<typeof createContext>;
My isAuthed tRPC middleware setup
const isAuthed = tRPC.middleware(async ({ next, ctx }) => {
console.log('isAuthed', ctx.auth);
if (ctx.auth.userId === null) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: {
auth: ctx.auth,
},
});
});
const isAuthed = tRPC.middleware(async ({ next, ctx }) => {
console.log('isAuthed', ctx.auth);
if (ctx.auth.userId === null) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: {
auth: ctx.auth,
},
});
});
GitHub
GitHub - trpc/examples-next-app-dir
Contribute to trpc/examples-next-app-dir development by creating an account on GitHub.
0 Replies
No replies yetBe the first to reply to this messageJoin