Correct way to add clerk auth to trpc

Hi, after 3 days of learning t3stack, i encounter some problems trying to create an privateProcedure, that using getAuth from and passing the "req", does not work, showing something like headers not defined, so i tried to modify api route, to only pass req, and not headers but also not working, im using app router, and i search on internet, and all solutions is for pages router, TypeError: Cannot read properties of undefined (reading 'headers'); The error will be redacted in production builds example code
const createContext = async (req: NextRequest) => {
return createTRPCContext({
headers: req.headers,
});
};
const createContext = async (req: NextRequest) => {
return createTRPCContext({
headers: req.headers,
});
};
import * as trpc from '@trpc/server'
import * as trpcNext from '@trpc/server/adapters/next'
import { getAuth } from '@clerk/nextjs/server'

export const createContext = async (opts: trpcNext.CreateNextContextOptions) => {
return { auth: getAuth(opts.req) }
}
import * as trpc from '@trpc/server'
import * as trpcNext from '@trpc/server/adapters/next'
import { getAuth } from '@clerk/nextjs/server'

export const createContext = async (opts: trpcNext.CreateNextContextOptions) => {
return { auth: getAuth(opts.req) }
}
but i found one dev.to blog, that shows the same problem that me, and the way he found to fix it, is use currentUser from next js, and seems to work fine, but is this the correct way to do it? t3stack seems to be an amazing way to create apps, but i think we do not have alot of docs or guides to use it.
export const createTRPCContext = async (opts: { headers: Headers }) => {
const user = await currentUser();

return {
db,
user,
...opts,
};
};
export const createTRPCContext = async (opts: { headers: Headers }) => {
const user = await currentUser();

return {
db,
user,
...opts,
};
};
1 Reply
Sugan_Selvam
Sugan_Selvam7d ago
Hey, the docs arent very clear about it. But instead of ‘auth: getAuth(opts.req)’ Just do ‘auth : await auth()’

Did you find this page helpful?