Next.js Discord

Discord Forum

Auth.js v5 and Mongoose error

Unanswered
MeKa posted this in #help-forum
Open in Discord
I added Mongoose before installing Auth.js v5 and the connection was successful, but after adding auth.js v5 it started giving errors.

When I add Middleware.ts these errors appear. I had previously added the "@auth/mongodb-adapter" and "mongodb" packages. I defined the adapter in the "/lib/auth.ts" file. I removed it thinking maybe it was a mistake. As I said, these errors appear when I add the middleware.ts file.

7 Replies

lib/db.ts
import mongoose from "mongoose";

const connection: { isConnected?: number } = {};

export const connectMongoDB = async () => {
  try {
    if (connection.isConnected) {
      console.log("Existing connection is being used");
      return;
    }
    const db = await mongoose.connect(process.env.MONGODB_URI as string);

    // readyState değeri 1 ise bağlantı mevcuttur.
    // Aksi takdirde 0'dır.
    connection.isConnected = db.connections[0].readyState;
    console.log("Connection successful.");
  } catch (error: any) {
    console.log("An error occurred during connection => ", error.message);
  }
};

export default connectMongoDB;
lib/auth.ts
import NextAuth from "next-auth";
import authConfig from "@/lib/auth.config";

export const { handlers, auth, signIn, signOut } = NextAuth({
  debug: true,
  secret: process.env.AUTH_SECRET,
  ...authConfig,
});
auth.config.ts
import type { NextAuthConfig } from "next-auth";

import Credentials from "next-auth/providers/credentials";
import { signInSchema } from "@/lib/zod";
import { saltAndHashPassword } from "./bcryptPass";
import User from "@/models/User";

export default {
  providers: [
    Credentials({
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (credentials) => {
        let user = null;
        const { email, password } = await signInSchema.parseAsync(credentials);

        if (!user) {
          throw new Error("User not found.");
        }

        const pwHash = saltAndHashPassword(password, user?.password);

        if (!pwHash) {
          throw new Error("Password comparison is incompatible");
        }
        // console.log(user);

        return user;
      },
    }),
  ],
  session: { strategy: "jwt" },
  pages: {
    signIn: "/auth/login",
    newUser: "/auth/register",
  },
  callbacks: {
    authorized({ auth }) {
      const isAuthenticated = !!auth?.user;
      return isAuthenticated;
    },
    jwt({ token, user }) {
      if (user) {
        token.id = user.id;
      }
      return token;
    },
    session({ session, token }) {
      session.user.id = token.id as string;
      return session;
    },
  },
} satisfies NextAuthConfig;
models/User.ts
import mongoose, { Schema } from "mongoose";

const userSchema = new Schema(
  {
    username: { type: String, unique: true, required: true },
    firstName: String,
    lastName: String,
    email: { type: String, required: true, unique: true },
    emailVerified: Date,
    password: { type: String, required: true },
    image: String,
    role: { type: String, enum: ["user", "admin"], default: "user" },
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
    accounts: [{ type: Schema.Types.ObjectId, ref: "Account" }],
    sessions: [{ type: Schema.Types.ObjectId, ref: "Session" }],
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now, index: true },
  },
  { timestamps: true, collection: "users" }
);

const User = mongoose.models.User || mongoose.model("User", userSchema);
export default User;
ERROR;

GET / 404 in 22ms
 ○ Compiling /_not-found ...
 ⨯ models\User.ts (23:1) @ <unknown>
 ⨯ Cannot read properties of undefined (reading 'User')
  21 | );
  22 |
> 23 | const User = mongoose.models.User || mongoose.model("User", userSchema);
     | ^
  24 | export default User;
middleware.ts
export { auth as middleware } from "auth"