Next-Auth signout error: TypeError: Response body object should not be disturbed or locked

I was writing a website with signIn and signOut function from next-auth/react. But sometimes when I sign out, error showing TypeError: Response body object should not be disturbed or locked shows on the terminal. Although it sometimes still signOut properly, but other times it just redirect to the main page and I have to click the signOut button again to signOut. I guess the problem occurs in how I handle signIn and here’s my code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const handleSubmit = async(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const result=await signIn("credentials", {
email,
password,
callbackUrl: `${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`,
redirect:false,
});
if((result)&&(result.error==="CredentialsSignin")){
toast({
variant: "destructive",
description: "輸入的帳號不存在或有誤,請再次輸入",
});
}
else if(result&&result.error==="CallbackRouteError"){
toast({
variant: "destructive",
description: "輸入的密碼不正確,請再次輸入",
});
}
else if (result && !result.error) {
router.push(`${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`);
router.refresh();
setOpen(false);
}
};
</code>
<code>const handleSubmit = async(e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const result=await signIn("credentials", { email, password, callbackUrl: `${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`, redirect:false, }); if((result)&&(result.error==="CredentialsSignin")){ toast({ variant: "destructive", description: "輸入的帳號不存在或有誤,請再次輸入", }); } else if(result&&result.error==="CallbackRouteError"){ toast({ variant: "destructive", description: "輸入的密碼不正確,請再次輸入", }); } else if (result && !result.error) { router.push(`${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`); router.refresh(); setOpen(false); } }; </code>
const handleSubmit = async(e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const result=await signIn("credentials", {
      email,
      password,
      callbackUrl: `${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`,
      redirect:false,
    });
    if((result)&&(result.error==="CredentialsSignin")){
      toast({
        variant: "destructive",
        description: "輸入的帳號不存在或有誤,請再次輸入",
      });
    }
    else if(result&&result.error==="CallbackRouteError"){
      toast({
        variant: "destructive",
        description: "輸入的密碼不正確,請再次輸入",
      });
    }
    else if (result && !result.error) {
      
      router.push(`${publicEnv.NEXT_PUBLIC_BASE_URL}/AboutMe`);
      router.refresh();
      setOpen(false);
    }
  };

And here’s my CredentialsProvider.ts:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { desc, eq } from "drizzle-orm";
import { db } from "@/db";
import { experiencesTable, usersTable } from "@/db/schema";
import { authSchema } from "@/validators/auth";
export default CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "text" },
username: { label: "Userame", type: "text", optional: true },
password: { label: "Password", type: "password"},
mobile:{ label:"Mobile", type:"text", optional: true},
school:{ label:"School", type:"text", optional: true}
},
async authorize(credentials) {
let validatedCredentials: {
email: string;
username?: string;
password: string;
mobile?:string;
school?:string;
};
try {
validatedCredentials = authSchema.parse(credentials);
} catch (error) {
console.log("Wrong credentials. Try again.");
return null;
}
const { email, password } = validatedCredentials;
const [existedUser] = await db
.select({
id: usersTable.displayId,
username: usersTable.username,
email: usersTable.email,
provider: usersTable.provider,
hashedPassword: usersTable.hashedPassword,
mobile: usersTable.mobile,
authority: usersTable.authority,
school: experiencesTable.school
})
.from(usersTable)
.leftJoin(experiencesTable, eq(usersTable.email, experiencesTable.email))
.orderBy(desc(experiencesTable.semester))
.where(eq(usersTable.email, email.toLowerCase()))
.limit(1)
.execute();
if(!existedUser){
return null;
}
const isValid = await bcrypt.compare(password, existedUser.hashedPassword);
if (!isValid) {
throw new Error("輸入的密碼不正確,請再次輸入");
}
return {
email: existedUser.email,
username: existedUser.username,
id: existedUser.id,
mobile: existedUser.mobile,
authority:existedUser.authority,
school: existedUser.school??""
};
},
});
</code>
<code>import CredentialsProvider from "next-auth/providers/credentials"; import bcrypt from "bcryptjs"; import { desc, eq } from "drizzle-orm"; import { db } from "@/db"; import { experiencesTable, usersTable } from "@/db/schema"; import { authSchema } from "@/validators/auth"; export default CredentialsProvider({ name: "credentials", credentials: { email: { label: "Email", type: "text" }, username: { label: "Userame", type: "text", optional: true }, password: { label: "Password", type: "password"}, mobile:{ label:"Mobile", type:"text", optional: true}, school:{ label:"School", type:"text", optional: true} }, async authorize(credentials) { let validatedCredentials: { email: string; username?: string; password: string; mobile?:string; school?:string; }; try { validatedCredentials = authSchema.parse(credentials); } catch (error) { console.log("Wrong credentials. Try again."); return null; } const { email, password } = validatedCredentials; const [existedUser] = await db .select({ id: usersTable.displayId, username: usersTable.username, email: usersTable.email, provider: usersTable.provider, hashedPassword: usersTable.hashedPassword, mobile: usersTable.mobile, authority: usersTable.authority, school: experiencesTable.school }) .from(usersTable) .leftJoin(experiencesTable, eq(usersTable.email, experiencesTable.email)) .orderBy(desc(experiencesTable.semester)) .where(eq(usersTable.email, email.toLowerCase())) .limit(1) .execute(); if(!existedUser){ return null; } const isValid = await bcrypt.compare(password, existedUser.hashedPassword); if (!isValid) { throw new Error("輸入的密碼不正確,請再次輸入"); } return { email: existedUser.email, username: existedUser.username, id: existedUser.id, mobile: existedUser.mobile, authority:existedUser.authority, school: existedUser.school??"" }; }, }); </code>
import CredentialsProvider from "next-auth/providers/credentials";

import bcrypt from "bcryptjs";
import { desc, eq } from "drizzle-orm";

import { db } from "@/db";
import { experiencesTable, usersTable } from "@/db/schema";
import { authSchema } from "@/validators/auth";

export default CredentialsProvider({
  name: "credentials",
  credentials: {
    email: { label: "Email", type: "text" },
    username: { label: "Userame", type: "text", optional: true },
    password: { label: "Password", type: "password"},
    mobile:{ label:"Mobile", type:"text", optional: true},
    school:{ label:"School", type:"text", optional: true}
  },
  async authorize(credentials) {
    let validatedCredentials: {
      email: string;
      username?: string;
      password: string;
      mobile?:string;
      school?:string;
    };

    try {
      validatedCredentials = authSchema.parse(credentials);
    } catch (error) {
      console.log("Wrong credentials. Try again.");
      return null;
    }
    const { email, password } = validatedCredentials;

    const [existedUser] = await db
      .select({
        id: usersTable.displayId,
        username: usersTable.username,
        email: usersTable.email,
        provider: usersTable.provider,
        hashedPassword: usersTable.hashedPassword,
        mobile: usersTable.mobile,
        authority: usersTable.authority,
        school: experiencesTable.school
      })
      .from(usersTable)
      .leftJoin(experiencesTable, eq(usersTable.email, experiencesTable.email))
      .orderBy(desc(experiencesTable.semester))
      .where(eq(usersTable.email, email.toLowerCase()))
      .limit(1)
      .execute();
    if(!existedUser){
      return null;
    }
    const isValid = await bcrypt.compare(password, existedUser.hashedPassword);
    if (!isValid) {
      throw new Error("輸入的密碼不正確,請再次輸入");
    }
    return {
      email: existedUser.email,
      username: existedUser.username,
      id: existedUser.id,
      mobile: existedUser.mobile,
      authority:existedUser.authority,
      school: existedUser.school??""
    };
  },
});

The signIn and signOut works fine before I add result(the variable returned in signIn function) and throw new Error in CredentialsProvider.ts(before both !existedUser and !isValid return null), so the error might occurs because of router.push() and router.refresh().
Because I want to toast different words when users type their account and password wrong, so I guess I still needs result(the variable returned in signIn function) to see if it is a CredentialsSignin error or CallbackRouteError.

I want to know whether my guess of why the error is showing is right and how to fix it without removing the part where I determine what kind of error is the signIn function returning. Thanks!

Providing my auth/signout if needed:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"use client";
import { useEffect } from "react";
import { signOut, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { publicEnv } from "@/lib/env/public";
function SignOutPage() {
const { data: session } = useSession();
const router = useRouter();
useEffect(() => {
if (session) {
signOut({ callbackUrl: publicEnv.NEXT_PUBLIC_BASE_URL });
}
router.push("/");
}, [session, router]);
return <></>;
}
export default SignOutPage;
</code>
<code>"use client"; import { useEffect } from "react"; import { signOut, useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import { publicEnv } from "@/lib/env/public"; function SignOutPage() { const { data: session } = useSession(); const router = useRouter(); useEffect(() => { if (session) { signOut({ callbackUrl: publicEnv.NEXT_PUBLIC_BASE_URL }); } router.push("/"); }, [session, router]); return <></>; } export default SignOutPage; </code>
"use client";

import { useEffect } from "react";

import { signOut, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

import { publicEnv } from "@/lib/env/public";

function SignOutPage() {
  const { data: session } = useSession();
  const router = useRouter();
  useEffect(() => {
    if (session) {
      signOut({ callbackUrl: publicEnv.NEXT_PUBLIC_BASE_URL });
    }
    router.push("/");
  }, [session, router]);

  return <></>;
}

export default SignOutPage;

Also how I signOut:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><a href="/auth/signout" className="hover:opacity-70">登出</a>
</code>
<code><a href="/auth/signout" className="hover:opacity-70">登出</a> </code>
<a href="/auth/signout" className="hover:opacity-70">登出</a>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật