Cannot access 't' before initialization

Hi, I'm migrating my app to a mono repo but I just can't get past this error for some reason Cannot access 't' before initialization when using the tRPC instance anywhere be it a middleware or router The server is a standalone node server useAuthenticaton.ts
import { TRPCError } from '@trpc/server'
import { t, User } from '../server/api'
import * as Auth from '../services/auth/auth'

const useAuthentication = t.middleware(async ({ ctx, next }) => {
try {
const authToken = ctx.req.headers['token'] as string
const authResult = (await Auth.verifyJWTToken(authToken)) as User

return next({
ctx: {
user: authResult
}
})
} catch (error) {
throw new TRPCError({
code: 'UNAUTHORIZED'
})
}
})

export default useAuthentication
import { TRPCError } from '@trpc/server'
import { t, User } from '../server/api'
import * as Auth from '../services/auth/auth'

const useAuthentication = t.middleware(async ({ ctx, next }) => {
try {
const authToken = ctx.req.headers['token'] as string
const authResult = (await Auth.verifyJWTToken(authToken)) as User

return next({
ctx: {
user: authResult
}
})
} catch (error) {
throw new TRPCError({
code: 'UNAUTHORIZED'
})
}
})

export default useAuthentication
api.ts
export type User = JwtPayload & {
userid: number
email: string
}

export type Context = inferAsyncReturnType<typeof createContext>

export type ServerContext = { user: User } & Context

export const t = initTRPC
.context<ServerContext>()
.meta<OpenApiMeta>()
.create({
transformer: superjson,
errorFormatter: ({ error, shape }) => {
if (
error.code === 'INTERNAL_SERVER_ERROR' &&
process.env.NODE_ENV === 'production'
) {
return { ...shape, message: 'Internal server error' }
}
return shape
}
})
export type User = JwtPayload & {
userid: number
email: string
}

export type Context = inferAsyncReturnType<typeof createContext>

export type ServerContext = { user: User } & Context

export const t = initTRPC
.context<ServerContext>()
.meta<OpenApiMeta>()
.create({
transformer: superjson,
errorFormatter: ({ error, shape }) => {
if (
error.code === 'INTERNAL_SERVER_ERROR' &&
process.env.NODE_ENV === 'production'
) {
return { ...shape, message: 'Internal server error' }
}
return shape
}
})
K
kevin.hill.fortunabmc331d ago
You could try exporting aliases of the functions? like this? Then maybe you will keep the reference of t in the one file
N
NEO331d ago
Turns out I can't define middlewares in a separate file, moving them under the api.ts solved the issue for me
K
kevin.hill.fortunabmc331d ago
You can do this
K
kevin.hill.fortunabmc331d ago
K
kevin.hill.fortunabmc331d ago
and create folders to house scoped procedures
K
kevin.hill.fortunabmc331d ago
this is procedures.ts
N
NEO331d ago
Interesting, I might try this, wasted so much time on this already haha
K
kevin.hill.fortunabmc331d ago
I have too, so I am happy to share what I've learned I posted my own discussion here if you want to check it out https://discord.com/channels/867764511159091230/1111426709519093840 I used it to have a bunch of different, service-specific, scoped procedures that have the proper clients attached asanaProcedure, salesforceProcedure, etc..
K
kevin.hill.fortunabmc331d ago
My router is insanely huge
N
NEO331d ago
I don't have subrouters instead a route file that has multiple procedures
N
NEO331d ago
Was trying your approach to middleware doesn't seem like it would work for chaining multiple middlewares
N
NEO331d ago
Came with a new solution, this passes the tRPC instance as a parameter to the middleware and you can still chain multiple middlewares together
More Posts
tRPC Middleware consuming memory limit on VercelHi all, I'm running into a weird error where my tRPC middleware to enforce that a user is authed, isUsing react-query parameters in tRPC for useQueryHello, the useQuery from react-query can take parameters such cacheTime, staleTime, refetchOnWindowFtRPC type error on turborepo```Types of property 'query' are incompatible. Type 'inferHandlerFn<{}>' is not assignable to tyStack for expo?Can someone recommend a stack for an expo project? I'm considering trpc + fastify + fly.io, but havImplementing a "Prisma model converter middleware"Bit of a fancy name, but if you've ever worked with Symfonys param converters (especially the DoctriSenior Full Stack Developer is Ready.✍️ Skill Set HTML/CSS/JS, TS React/Next.js, Angular/RxJs, Tailwind CSS WoSuggested way to invalidate queries on a component that is used on multiple pages.Please suggest me a way I can handle the following situation in the best possinle manner. CoinsiderSetting up trpc behind AWS API gateway and authorizing using a lambdaCurrent setup: - trpc api, containing both public an private procedures. Let's call them `posts.listsetMutationDefaults for optimistic updatesI have a `preferences` router, with a `get` query and a `set` mutation. I had optimistic updates setUsing tRPC in React SPA with Django backendis that possible? Do I need to create an AppRouter and put that inside my django backend files? How Typing a shared TRPC provider for testingContext: - We have a monorepo with several micro-frontends which use Next. - We're moving to using tResponse promise resolves before endpoint finished processingI want to interact with OpenAI's API in my Next.js + tRPC app. It seems that the my frontend is not tRPC onErrorI am using tRPC with Fastify and would like to be able to report issues when we get an error. httpsCode structure for a large monorepo using nx + tRPCWe have a large monorepo with a single tRPC API that will be used by several web clients and other cDoes tRPC work with Clerk and Vercel Edge functions?So the answer is yes, at least locally, but I when I deploy to Vercel I get nothing. Trying to work TRPCClientError when creating a db entry without `updatedAt` value?Guys, this is my prisma schema: ``` model User { id Int @id @default(autoincrement()) Type error: The inferred type of 'trpc' cannot be named without a reference....```./src/lib/api.ts:21:14 @driveorg/dashboard:build: Type error: The inferred type of 'trpc' cannot Decision on authI am using create-t3-app for my app , with next-auth (twitter, discord, google) . Now i am using samWhy does this starter with Prisma have it's own postinstall script?Prisma has it's own postinstall hook/script: <https://www.prisma.io/docs/concepts/components/prisma-Senior Full Stack Developer is Ready.✍️ Skill Set HTML/CSS/JS, TS React/Next.js, Angular/RxJs, Tailwind CSS WordP