error - ReferenceError: Cannot access 'createTRPCRouter' before initialization

Anyone ever experience an error as in title of this Q. src\server\api\root.ts
import { createTRPCRouter } from "./trpc";
import { exampleRouter } from "./routers/example";
import { roleRouter } from "./routers/role";
export const appRouter = createTRPCRouter({
example: exampleRouter,
role: roleRouter,
.....
})
import { createTRPCRouter } from "./trpc";
import { exampleRouter } from "./routers/example";
import { roleRouter } from "./routers/role";
export const appRouter = createTRPCRouter({
example: exampleRouter,
role: roleRouter,
.....
})
If you change import order and move roleRouter import at top, it will throw error at roleRouter in below error description. Error Description:
{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{"__NEXT_PAGE":"/api/trpc/auth.getSecretMessage,auth.getAllPermissions"},"buildId":"development","isFallback":false,"err":{"name":"ReferenceError","source":"server","message":"Cannot access 'createTRPCRouter' before initialization","stack":"ReferenceError: Cannot access 'createTRPCRouter' before initialization\n at Module.createTRPCRouter (webpack-internal:///(api)/./src/server/api/trpc.ts:5:65)\n at eval (webpack-internal:///(api)/./src/server/api/routers/example.ts:12:61)"},"gip":true,"locales":["en"],"scriptLoader":[]}
{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{"__NEXT_PAGE":"/api/trpc/auth.getSecretMessage,auth.getAllPermissions"},"buildId":"development","isFallback":false,"err":{"name":"ReferenceError","source":"server","message":"Cannot access 'createTRPCRouter' before initialization","stack":"ReferenceError: Cannot access 'createTRPCRouter' before initialization\n at Module.createTRPCRouter (webpack-internal:///(api)/./src/server/api/trpc.ts:5:65)\n at eval (webpack-internal:///(api)/./src/server/api/routers/example.ts:12:61)"},"gip":true,"locales":["en"],"scriptLoader":[]}
16 Replies
JacobMGEvans
JacobMGEvans2y ago
The error message "Cannot access 'createTRPCRouter' before initialization" suggests that the function is being called before it has been properly initialized. This could be caused by a variety of issues in the code, such as a missing import statement, a circular dependency, or a lack of proper initialization logic. What have you done to look into this before posting?
vilchy ✓
vilchy ✓2y ago
Currently having same problem. It disappears after doing any change in any file and saving it. But when I rerun the project it comes back.
vilchy ✓
vilchy ✓2y ago
Here is how browser shows my error
nimeshvaghasiya
I have look into https://github.com/trpc/trpc/issues/3081 trpc repo. issue but coudn't figure out exact issue. It returns me 500 error with text/html response. I'm signing in using nextauth discord/google provider, and redirecting user to callbackUrl (dashboard), then calling some trpc routes to get permissioned navigation menu items. but trpc throws 500 with html text response.
GitHub
httpLink/httpBatchLink on fetch redirect · Issue #3081 · trpc/trpc
Provide environment information System: OS: macOS 11.6.8 CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 610.94 MB / 32.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 18.11.0 - ~/.nvm/v...
JacobMGEvans
JacobMGEvans2y ago
Not sure how that issue relates. You may need to provide a repro with that error message (the imports dont count as a repro) & the steps to reproduce. https://stackoverflow.com/help/minimal-reproducible-example
Stack Overflow
How to create a Minimal, Reproducible Example - Help Center
Stack Overflow | The World’s Largest Online Community for Developers
vilchy ✓
vilchy ✓2y ago
i found the line that causes the error but idk how else should i tackle this issue. So i wanted only approved accounts to log in so i made a signin callback which calls trpc to check if requesting user is approved (sort of a whitelist).
async signIn({ user }) {
// If the user is not verified, don't let them sign in
const ctx = createInnerTRPCContext({ session: null });
const caller = usersRouter.createCaller(ctx);
const data = await caller.isApproved({ id: user.id });
if (!data?.verified) {
return false;
} else {
return true;
}
},
async signIn({ user }) {
// If the user is not verified, don't let them sign in
const ctx = createInnerTRPCContext({ session: null });
const caller = usersRouter.createCaller(ctx);
const data = await caller.isApproved({ id: user.id });
if (!data?.verified) {
return false;
} else {
return true;
}
},
JacobMGEvans
JacobMGEvans2y ago
If you change import order and move roleRouter import at top, it will throw error at roleRouter in below error description.
import { createTRPCRouter } from "./trpc"; Likely needs to be first to initialize the Router, import order can matter.
vilchy ✓
vilchy ✓2y ago
const caller = usersRouter.createCaller(ctx);
const caller = usersRouter.createCaller(ctx);
JacobMGEvans
JacobMGEvans2y ago
I am getting a feeling this is a different issue
vilchy ✓
vilchy ✓2y ago
without this line, it works I needed to put import of createInnerTRPCContext above import of usersRouter in [...nextauth].ts now it works form me thanks for guiding me on the badly ordered imports trope
JacobMGEvans
JacobMGEvans2y ago
lol
nimeshvaghasiya
I have found exact issue which is causing an error. you can't use "createTRPCContext" inside next auth signIn callback even if you wrap auth options to access NextApiRequest and NextApiResponse, I need to wrap it because i need some cookie values. Using "createInnerTRPCContext" does fix an error:
const ctx = await createInnerTRPCContext({ session: null });
const caller = appRouter.createCaller(ctx);
const ctx = await createInnerTRPCContext({ session: null });
const caller = appRouter.createCaller(ctx);
Code (signIn callback lines produce unusual error as mentioned in title):
export const authOptions = (req: NextApiRequest | undefined = undefined, res: NextApiResponse | undefined = undefined): NextAuthOptions => {
return {
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
const ctx = await createTRPCContext({ req, res });
const caller = appRouter.createCaller(ctx);
caller.role.getAllPermissions({...})
...
}
}
...
}
};

// export default NextAuth(authOptions);
export default (req: NextApiRequest, res: NextApiResponse) => {
return NextAuth(req, res, authOptions(req, res))
}
export const authOptions = (req: NextApiRequest | undefined = undefined, res: NextApiResponse | undefined = undefined): NextAuthOptions => {
return {
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
const ctx = await createTRPCContext({ req, res });
const caller = appRouter.createCaller(ctx);
caller.role.getAllPermissions({...})
...
}
}
...
}
};

// export default NextAuth(authOptions);
export default (req: NextApiRequest, res: NextApiResponse) => {
return NextAuth(req, res, authOptions(req, res))
}
@0𝙚𝙪𝙚 ✓ @JacobMGEvans Do you think using "createTRPCContext" anywhere should not cause any issue?
nimeshvaghasiya
I have created latest create t3 app: https://github.com/nimeshvaghasiya/t3routererror Steps to reproduce error: - Clone above repository, do npm install then npm run dev - Click on "Roles" - Click on "Sign in" button : throws error - If you comment out signin callback, there will be no error. @JacobMGEvans @0𝙚𝙪𝙚 ✓ I would like to open an issue to t3app github repo, if someone can confirm this is a real issue.
GitHub
GitHub - nimeshvaghasiya/t3routererror
Contribute to nimeshvaghasiya/t3routererror development by creating an account on GitHub.
JacobMGEvans
JacobMGEvans2y ago
Just open an issue, if its not an issue to them they will tell you.
Stivo
Stivo2y ago
Any updates? I'm having the same issue
Want results from more Discord servers?
Add your server