Next.js Discord

Discord Forum

Next Auth Error with Credential provider

Answered
Red wood ant posted this in #help-forum
Open in Discord
Red wood antOP
Hello I am currently developing a multi-tenant project using Next.js, Prisma, PostgreSQL, and Vercel for deployment.

Right now, I am looking to set up a credential provider. I have already implemented the Google provider and the GitHub provider, which are working very well, but I am having trouble setting up the credential provider.

My credential provider always receives an error, which I see when I inspect the network... I don't understand where it could be coming from. I am new to Next.js, so I still have some difficulties...
Answered by Red wood ant
I fixed it , i added e.preventDefault before the signin("credential") I don't know why it was blocking but now it's working
View full answer

7 Replies

Red wood antOP
my file auth.ts
export const authOptions: NextAuthOptions = {
  providers: [

    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {

        if (!credentials || !credentials.email || !credentials.password) {
          return null;
        }
      
        const client = await prisma.client.findUnique({
          where: { email: credentials.email },
        });

        if (!client || !(await bcrypt.compare(credentials.password, client.password))) {
          return null;
        }

        console.log({client})
        return {
          id : client.id,
          username: client.username,
          email : client.email
        }
      },
    }),
    
    GitHubProvider({
      clientId: process.env.AUTH_GITHUB_ID as string,
      clientSecret: process.env.AUTH_GITHUB_SECRET as string,
      profile(profile) {
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          gh_username: profile.login,
          email: profile.email,
          image: profile.avatar_url,
        };
      },
    }),
pages: {
    signIn: `/login`,
    verifyRequest: `/login`,
    error: "/login", // Error code passed in query string as ?error=
  },
  adapter: PrismaAdapter(prisma),
  session: { strategy: "jwt" },
  cookies: {
    sessionToken: {
      name: `${VERCEL_DEPLOYMENT ? "__Secure-" : ""}next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: "lax",
        path: "/",
        // When working on localhost, the cookie domain must be omitted entirely (https://stackoverflow.com/a/1188145)
        // domain: VERCEL_DEPLOYMENT
        //   ? `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`
        //   : undefined,
        // secure: VERCEL_DEPLOYMENT,
      },
    },
  },
  callbacks: {
    jwt: async ({ token, user }) => {
      if (user) {
        token.user = user;
      }
      return token;
    },
async session({ session, token }) {

        session.user = {
          ...session.user,
        // @ts-expect-error
        id: token.sub,
        // @ts-expect-error
        username: token?.user?.username || token?.user?.gh_username,
        
        };
      
      return session;
    },
  },
};

export function getSession() {
  return getServerSession(authOptions) as Promise<{
    user: {
      id: string;
      name: string;
      username: string;
      email: string;
      image: string;
    };
  } | null>;
}
My form

const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

     // Get error message added by next/auth in URL.
  const searchParams = useSearchParams();
  const error = searchParams?.get("error");

  useEffect(() => {
    const errorMessage = Array.isArray(error) ? error.pop() : error;
    errorMessage && toast.error(errorMessage);
  }, [error]);
    
    const handleLogin = async () => {
        const result = await signIn("credentials", {
          email,
          password,
        }).then(res => {
            if (res?.error === null) {
              // Handle successful login
              console.log(result);
            } else {
              // Handle error
              console.log(res?.error);
            }
          });;
      };
return (
          <form onSubmit={handleLogin} className="mt-4 mx-auto w-11/12 max-w-xs sm:w-full">
            <div className="mb-4">
              <label htmlFor="email" className="block text-sm font-medium text-stone-600 dark:text-stone-400">
                Username
              </label>
              <input
                name="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1 p-2 border rounded-md w-full focus:outline-none focus:ring focus:ring-black dark:bg-black dark:text-white"
                required
              />
            </div>
            <div className="mb-6">
              <label htmlFor="password" className="block text-sm font-medium text-stone-600 dark:text-stone-400">
                Password
              </label>
              <input
                name="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-1 p-2 border rounded-md w-full focus:outline-none focus:ring focus:ring-black dark:bg-black dark:text-white"
                required
              />
            </div>
            <button type="submit" className="bg-black text-white py-2 px-4 rounded-md w-full hover:bg-opacity-80 transition duration-300 ease-in-out focus:outline-none focus:ring focus:ring-black">
              Sign In
            </button>
          </form>
      );
}
here is the error in image
Red wood antOP
I fixed it , i added e.preventDefault before the signin("credential") I don't know why it was blocking but now it's working
Answer