NextAuth.js signIn response always undefined

45 Views Asked by At

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.

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.0

  • My Node.Js version is 20.12.0

I have tried:

  • Upgrading my Node Version [Here]
1

There are 1 best solutions below

3
Arash Jahan Bakhshan On

On the app router, you should use version 5 of next auth which is currently in beta. I will show you step-by-step to how migrate your code to V5.

Step 1: Update next-auth dependency
npm install [email protected]
Step 2: Change the code in the route.js file
util/auth.js
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'

const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

export const authConfig = {
  providers: [
    Credentials({
      name: 'Credentials',
      credentials: {
        username: { label: 'username', type: 'text' },
        password: { label: 'password', type: 'password' }
      },
      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 const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth(authConfig);
app/api/auth/[...nextauth]/route.js
export { GET, POST } from "../../../../util/auth.js";
Step 3: SignIn the user

Keep in mind that the signIn, signOut and auth functions should run on the server side and NOT in client. You can put signIn and signOut in the server actions to use them:

import { auth, signIn } from "util/auth.js"

export const MyServerComponent = async () => {
    const session = await auth();

    if(session) {
        redirect("/");
    }
 
    return (
        <div>
            <button 
                formAction={async () => {
                    "use server";

                    await signIn("Credentials");
                }}
            >
                Sign In
            </button>
        </div>
    );
}