Issue with trpc fetch when trying to pass Clerk auth to context
I'm currently trying to add Clerk auth to my trpc context, but I just keep getting this error:
This is my code:
Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSONError: Unexpected token '<', "<!DOCTYPE "... is not valid JSONThis is my code:
context.tscontext.tsimport { NextRequest } from 'next/server'
import { getAuth } from '@clerk/nextjs/server'
import { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch'
export function createContext(opts: FetchCreateContextFnOptions) {
const auth = getAuth(opts.req as NextRequest)
return {
auth,
headers: opts && Object.fromEntries(opts.req.headers)
}
}
export type Context = Awaited<ReturnType<typeof createContext>>import { NextRequest } from 'next/server'
import { getAuth } from '@clerk/nextjs/server'
import { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch'
export function createContext(opts: FetchCreateContextFnOptions) {
const auth = getAuth(opts.req as NextRequest)
return {
auth,
headers: opts && Object.fromEntries(opts.req.headers)
}
}
export type Context = Awaited<ReturnType<typeof createContext>>trpc.tstrpc.tsimport { TRPCError, initTRPC } from '@trpc/server'
import superjson from 'superjson'
import { ZodError } from 'zod'
import { Context } from './context'
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter(opts) {
const { shape, error } = opts
return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null
}
}
}
})
const isAuthed = t.middleware(({ next, ctx }) => {
console.log('isAuthed', ctx.auth)
if (!ctx.auth.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' })
}
return next({
ctx: {
auth: ctx.auth
}
})
})
export const router = t.router
export const publicProcedure = t.procedure
export const protectedProcedure = t.procedure.use(isAuthed)import { TRPCError, initTRPC } from '@trpc/server'
import superjson from 'superjson'
import { ZodError } from 'zod'
import { Context } from './context'
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter(opts) {
const { shape, error } = opts
return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null
}
}
}
})
const isAuthed = t.middleware(({ next, ctx }) => {
console.log('isAuthed', ctx.auth)
if (!ctx.auth.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' })
}
return next({
ctx: {
auth: ctx.auth
}
})
})
export const router = t.router
export const publicProcedure = t.procedure
export const protectedProcedure = t.procedure.use(isAuthed)