Next.js Discord

Discord Forum

Client must be connected before running operations

Unanswered
Mike posted this in #help-forum
Open in Discord
I have the following error. I tried in a few ways to fix him but i didnt can.

I am proud about every help.

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import dbConnect from "@/utils/connectDB";
import User from "@/models/User";
import mongoose from "mongoose";

const auth = NextAuth({
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials, req) {
        try {
          // Verbindung zur Datenbank herstellen
          await dbConnect();

          const { email, password } = credentials;
          const user = await User.findOne({ email });
          if (!user) {
            throw new Error("Invalide E-Mail oder Passwort!");
          }
          const isPasswordMatched = await bcrypt.compare(password, user.password);
          if (!isPasswordMatched) {
            throw new Error("Invalide E-Mail oder Passwort!");
          }

          return user;
        } catch (error) {
          console.log(error);
          throw error;
        } finally {
          // Verbindung zur Datenbank schließen
          if (mongoose.connection.readyState === 1) {
            await mongoose.disconnect();
          }
        }
      },
    }),
  ],
  pages: {
    signIn: "/",
  },
  secret: process.env.NEXTAUTH_SECRET,
});

export { auth as POST, auth as GET, auth as nextAuthOptions };

9 Replies

Sloth bear
Maybe you wrote
await client.close();
Show dbConnect code
import mongoose from "mongoose";

const dbConnect = async () => {
  if (mongoose.connection.readyState >= 1) return;

  mongoose.connect(process.env.MONGO_URL);
};

export default dbConnect;
This is my db connect code
With .close() i cant login anymore
someone know why id doesnt weork?
Because I didn’t know thy it doesn’t work
Gray-spotted Flycatcher
Hello, please I have an error help me
@Gray-spotted Flycatcher Hello, please I have an error help me
Sloth bear
Create new #help-forum and post your problem