HuzefH
tRPC3y ago
15 replies
Huzef

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


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
    }
  })
Was this page helpful?