Whenever I run my authorize callback in NextAuth from my signIn function in my page, the result is undefined regardless of what I do. The page also refreshes immediately with the callbackUrl query.
I am using the Credentials Provider from NextAuth.
I am using the App Router from NextJs
This is my auth route:
// app/api/auth/[...nextauth]/route.js
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
const handler = NextAuth({
providers: [
Credentials({
name: 'Credentials',
credentials: {
username: { label: 'username', type: 'text' },
password: { label: 'password', type: 'password' }
},
})
],
callbacks: {
async authorize(credentials) {
// const { username, password } = credentials;
// mocking API request (doesn't work, just refreshes immediately)
await delay(3000);
try {
return { user: "Shiawase" };
} catch (error) {
throw new Error('Failed to authenticate user');
}
},
},
pages: {
signIn: '/auth/login'
}
});
export { handler as GET, handler as POST };
And this is my login logic within my page:
// app/auth/login/page.tsx
async function onSubmit(data: z.infer<typeof FormSchema>) {
setIsLoading(true);
const result = await signIn('Credentials', {
username: data.username,
password: data.password,
redirect: false
});
// result is undefined
console.log(result)
if (result) {
setIsLoading(false);
console.log("Successfully logged in")
setTimeout(() => {
router.push('/user/dashboard/home');
}, 2000);
} else {
setIsLoading(false);
console.log("Something unexpected occurred");
return;
}
}
My NextJs version is
14.1.0My Node.Js version is
20.12.0
I have tried:
- Upgrading my Node Version [Here]
On the app router, you should use version 5 of
next authwhich is currently in beta. I will show you step-by-step to how migrate your code to V5.Step 1: Update next-auth dependency
Step 2: Change the code in the
route.jsfileutil/auth.js
app/api/auth/[...nextauth]/route.js
Step 3: SignIn the user
Keep in mind that the
signIn,signOutandauthfunctions should run on the server side and NOT in client. You can putsignInandsignOutin the server actions to use them: