Reputation: 1892
I'm trying to use nextAuth for my authentication. I followed the documentation. I just found out that when I'm trying to login using credentials for the VERY FIRST TIME I will get null or undefined user even though my fetch request is successful.
import { AuthResponse } from "@/typings/Interface/AuthResponse"
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
credentials: {
email: {},
password: {},
},
authorize: async (credentials): Promise<any> => {
try {
let user: any = null;
const res = await fetch("localhost", {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(credentials),
});
const data: AuthResponse = await res.json();
return { ...data.user }
} catch (error) {
console.log(error, 'eeeee')
return null;
}
},
}),
],
session: {
strategy: 'jwt'
},
callbacks: {
async signIn({ user, account, profile, email, credentials }: any) {
if (user?.error === 'LoginError') {
throw new MyCustomeError()
}
return true;
},
async session({ session, token }: any) {
session.user = token.user;
return session;
},
async jwt({ token, user }) {
if (user) {
token.user = user;
}
return token;
}
}
})
I notice this when I tried to delete this cookie:
So first the very very first time the user tries to login and the cookies are empty the auth()
method returns nothing, but when you try to login again since the cookies from nextAuth are not empty it returns the correct object.
this is my login action and how I call the signIn
method:
await signIn("credentials", { ...formValues, redirect: false })
const awt = await auth();
console.log(awt, 'awawaawtaw') // <---- This is empty on the very first attempt of logging in
what I'm trying to do here is before I manually redirect I wanted to grab the user information and return it to the client side form because I'm using zustand and wanted to setup the user information before redirecting.
Upvotes: 0
Views: 16