UserID is null
Unanswered
Rough harvester ant posted this in #help-forum
Rough harvester antOP
I'm using a server rendered session provider:
//CustomSessionProvider.tsx
"use server"
import { SessionProvider } from 'next-auth/react'
import React, { ReactNode } from 'react'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
export default async function CustomSessionProvider({ children }: { children: ReactNode }) {
const session = await auth()
if (session == null || session == undefined) {
console.log("Session is null or undefined. Redirecting to /auth/signin.")
redirect('/auth/signin')
}
return (
<SessionProvider session={session}>
{children}
</SessionProvider>
)
}
//auth.ts
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
name: 'credentials',
async authorize(credentials) {
console.log("authorize called with credentials: ", credentials)
const parsedCredentials = z.object({ username: z.string(), password: z.string().min(6) })
.safeParse(credentials);
console.log("parsedCredentials: ", parsedCredentials)
if (parsedCredentials.success) {
const { username, password } = parsedCredentials.data;
const user: IUser | null = await getUser(username);
console.log("user: ", user)
if (!user) {
console.log("User not found.")
return null
};
const passwordsMatch = await bcrypt.compare(password, user.password);
if (passwordsMatch) {
console.log("Credentials are valid, returning user.", user)
return user;
}
}
return null;
}
})
]
})3 Replies
Rough harvester antOP
//layout.tsx (user area protected by auth)
import CustomSessionProvider from "@/components/auth/context/CustomSessionProvider";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<CustomSessionProvider>
{children}
</CustomSessionProvider>
);
}
//any child of <CustomSessionProvider>
export default function SomeChild() {
const userID = useSession().data?.user?.id;
if (userID == undefined) throw new Error("No user ID found");
return(JSON.stringify(userID))The userID is shown on screen for about 2 seconds then the 'No user ID' error is thrown
And
Session is null or undefined. Redirecting to /auth/signin. from CustomSessionProidver.tsx never logs in the console...Rough harvester antOP
I've done some digging and it looks like it gets the session details from my
SessionProvider but for some reason makes a further api call to /auth/api/session to get the current session (even though it already has it?!) which returns 404 (as I didn't need to make this route) which updates the session as unauthenticated. Is there any way I can stop it from making the call?