Session Callback Not Triggering in NextAuth Integration with tRPC #1142
Replies: 2 comments 5 replies
-
I wanted to share another discovery I made. When I added the Middleware - auth: null
│ ○ Compiling /api/trpc/[trpc] ...
│ ✓ Compiled /api/trpc/[trpc] in 2.3s (1096 modules)
│ >>> tRPC Request from admin-panel by undefined
│ Query: select "id", "name", "email", "emailVerified", "password", "image", "userType", "role" from "users" where ("
│ users"."email" = $1 and "users"."userType" = $2) limit $3 -- params: ["[email protected]", "admin", 1]
│ Query: select "id", "name", "email", "emailVerified", "password", "image", "userType", "role" from "users" where ("
│ users"."email" = $1 and "users"."userType" = $2) limit $3 -- params: ["[email protected]", "admin", 1]
│ Query: select "id", "name", "email", "emailVerified", "password", "image", "userType", "role" from "users" where "u
│ sers"."id" = $1 limit $2 -- params: ["8a3195a0-3cb2-048e-a613-412345539d782", 1]
│ JWT callback - token: {
│ name: 'Test Accountl',
│ email: '[email protected]',
│ picture: null,
│ sub: '8a3195a0-3cb2-048e-a613-412345539d782',
│ role: 'admin'
│ }
│ >>> tRPC Error on 'auth.adminSignIn' Error: NEXT_REDIRECT
│ at getRedirectError (webpack-internal:///(rsc)/../../node_modules/next/dist/client/components/redirect.js:49:19
│ )
│ ... 8 lines matching cause stack trace ...
│ at async eval (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-import/http/
│ resolveResponse.mjs:359:45) {
│ code: 'INTERNAL_SERVER_ERROR',
│ name: 'TRPCError',
│ [cause]: Error: NEXT_REDIRECT
│ at getRedirectError (webpack-internal:///(rsc)/../../node_modules/next/dist/client/components/redirect.js:49:
│ 19)
│ at redirect (webpack-internal:///(rsc)/../../node_modules/next/dist/client/components/redirect.js:60:11)
│ at signIn (webpack-internal:///(rsc)/../../node_modules/next-auth/lib/actions.js:59:76)
│ at async eval (webpack-internal:///(rsc)/../../packages/api/src/router/auth.ts:56:13)
│ at async resolveMiddleware (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-n
│ ot-import/procedureBuilder.mjs:110:30)
│ at async callRecursive (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-i
│ mport/procedureBuilder.mjs:160:32)
│ at async callRecursive (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-i
│ mport/procedureBuilder.mjs:160:32)
│ at async procedure (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-impor
│ t/procedureBuilder.mjs:190:24)
│ at async eval (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-import/htt
│ p/resolveResponse.mjs:207:30)
│ at async eval (webpack-internal:///(rsc)/../../node_modules/@trpc/server/dist/unstable-core-do-not-import/htt
│ p/resolveResponse.mjs:359:45) {
│ digest: 'NEXT_REDIRECT;replace;http://localhost:3000/dashboard;307;',
│ mutableCookies: f {
│ _parsed: [Map],
│ _headers: Headers {
│ 'set-cookie': 'authjs.callback-url=http%3A%2F%2Flocalhost%3A3000%2Fdashboard; Path=/; HttpOnly; SameSite=la
│ x, authjs.csrf-token=94b93310960146614352345231e16d3d24abdef2b89665a2d44a93ad35462d459d%7Cca2644451dfdfe84fd38d431de9
│ 4df44119df5df43bc7876af48c019885ffce5; Path=/, authjs.session-token=eyJhbGciOiJkaXIiLCJlbSDFSfdsSDFSQ0JDLUhTNTEyIiw
│ ia2lkIjoicHhfZVVOSUdvWnNBeEFsTUxtSmNjZjNWWVdkcFhzZ2cwOFdRVTBHN3UzM0tvem5vS1Q2asdfasdasdfasdfaafdahSRE
│ pfMFo2aUEifQ..W-7nOie__RAZ1kbagblw4g.cR7U5n8epiQPETinH3T-xtaag7WzRJ4u_8cZAw02oWR28L1VQ2Sg_zD8sYf-UyNH7enbqILGg9iqwY
│ S9pJSLZ6LyjEdh3VtsX5YOxlGFkc5vbrMGvcmLMlUwEJZ0QaX518oWxdmXMH5d1AmsS9NYagYrctRiPyjpcm3smVZwGJbaLb2cSXLi2qJIs0xQQk9Ci
│ AssSZ6ukKhtMHv7kMmr-hhMVeSiQUspA2dLnGVo92wd0RZRgcT7sNtthownvL7wHKoXC3PRIBZJFyRd4h0paUxF-lVPTJmwtWk0Uvgv_ts.19F_aU0x
│ TlVPwvHXBr2fKS-JrSk1v3LqCCKFqaEopTA; Path=/; Expires=Sun, 08 Sep 2024 23:18:14 GMT; HttpOnly; SameSite=lax'
│ }
│ }
│ }
│ }
│ POST /api/trpc/auth.adminSignIn?batch=1 200 in 3603ms Additionally, I tried printing the import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { appRouter, createTRPCContext } from "@acme/api";
import { auth } from "@acme/auth/admin";
export function OPTIONS() {
const response = new Response(null, { status: 204 });
setCorsHeaders(response);
return response;
}
const handler = auth(async (req) => {
const response = await fetchRequestHandler({
endpoint: "/api/trpc",
router: appRouter,
req,
createContext: () =>
createTRPCContext({
session: req.auth,
headers: req.headers,
}),
onError({ error, path }) {
console.error(`>>> tRPC Error on '${path}'`, error);
},
});
console.log("Response header:", response.headers);
setCorsHeaders(response);
return response;
});
export { handler as GET, handler as POST }; The headers don’t include the set-cookie property, which is likely why the session isn’t being set correctly. Since we can't do any redirects inside tRPC, I moved the redirect logic to the client, but I just wanted to share these findings with you. Let me know if you have any thoughts or if there's something specific you'd like me to try next. |
Beta Was this translation helpful? Give feedback.
-
Hello everyone,
I'm currently experiencing an issue with my Next.js application where the session callback in NextAuth is not being triggered as expected when using tRPC. I have a monorepo setup with two apps: an e-commerce app and an admin panel for managing the e-commerce app. The problem seems to be isolated to the admin panel, and the session callback works correctly when logging in with the Google provider but not with credentials.
Project Setup:
Problem Description:
The session callback is not being triggered when logging in with credentials, resulting in undefined session data being passed to tRPC context. However, when logging in with the Google provider, the session callback works correctly, and the session data is properly logged.
Logs:
Credentials Login Attempt:
Google Login Attempt:
Code :
Sign-In Page Using Credentials (with tRPC):
Google Sign-In Page (without tRPC):
NextAuth Configuration:
NextAuth export:
Auth Package Export:
Middleware Configuration:
API Route Handling:
tRPC Context Creation:
tRPC authRouter:
Help Needed:
I'm seeking assistance to understand why the session callback is not being triggered when using credentials and why the session data is not being correctly passed to tRPC context. Any insights or suggestions on what might be going wrong would be greatly appreciated.
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions