Search code examples
mongodbnext.jsnext-auth

Next-authjs issue with Mongodb


Below is my [...nextauth].js file and for some reason when I try and use it to login by going to http://localhost:3000/api/auth/signin it presents the username and password box but then when I submit it I get an error.

http://localhost:3000/api/auth/error?error=Illegal%20arguments%3A%20undefined%2C%20undefined

But it is not telling me what the illegal argument is, is there any way to find out?

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import clientPromise from "../../../lib/mongodb";
import jwt from "next-auth/jwt";
import { compare } from 'bcryptjs';

export default NextAuth({
    
  session: {
      jwt: true,
  },
    providers: [
        CredentialsProvider({
          // The name to display on the sign in form (e.g. 'Sign in with...')
          name: 'DRN1',
          credentials: {
            username: { label: "Username", type: "text"},
            password: {  label: "Password", type: "password" }
          },
          async authorize(credentials, req) {
          

            const client = await clientPromise
            const { fieldvalue } = req.query

            console.log("RUNNING THIS QUERY "+req.query)

            const database = client.db('DRN1');
            const users = await database.collection('users');
            const result = await users.findOne({
              username: credentials.username,
            });

            if (!result) {
              client.close();
              throw new Error('No user found with the username');
            }

            //Check hased password with DB password
            const checkPassword = await compare(credentials.passowrd, result.passowrd);
            //Incorrect password - send response
            if (!checkPassword) {
                client.close();
                throw new Error('Password doesnt match');
            }
            //Else send success response
            client.close();
            return { username: result.username };

          }
        })
      ],
      theme: {
        colorScheme: "dark", // "auto" | "dark" | "light"
        brandColor: "", // Hex color code
        logo: "https://storage.googleapis.com/radiomedia-images/station_logos/v2/DRN1_small.png" // Absolute URL to image
      }
});

Solution

  • In my case, the error was in comparing passwords. You need to check this string.

    const checkPassword = await compare(credentials.passowrd, result.passowrd);
    

    My credentials.password wasn't equal to result.password, becase I wrote

    const result = await users.findOne({
              username: credentials.username,
            });
    

    instead of

    const { result } = await users.findOne({
              username: credentials.username,
            });
    

    Hope, it will help. Good luck.