Next.js Discord

Discord Forum

Struggling with NextAuth with Custom Backend login APIs

Unanswered
hojomojo posted this in #help-forum
Open in Discord
Facing a snag with NextAuth integration while working with various backend login APIs. Followed the docs meticulously, but stuck in a loop redirecting to login post-authentication. Any insights? #NextAuth #AuthenticationIssues

5 Replies

give more insight of how you redirect the user. and if you are using middleware, I think its a wrong implimentation, matcher currently try to authenticate on... all next static files, you can find the regix to avoid it in nextjs doc. something like... (!api|_next) .....\
the problem you probably facing could be:
1. you are authenticated but session is not updated which lead the middleware redirect back you to login page.
2. your "signIn callback" implimentation is incorrect and user actually hasnt authenticated. maybe impliment a bit more. or try to debug from the signin inputs to up until where it doesn't make any sense 🙂
here is the signin function which im using on my custom login page:
const onSubmit = async (data: FormData) => {
console.log("Submitting form", data);

const { email, password } = data;

try {
const response: any = await signIn("credentials", {
email,
password,
redirect: false,
});
console.log({ response });
if (!response?.error) {
router.push("/");
router.refresh();
}

if (!response.ok) {
throw new Error("Network response was not ok");
}
// Process response here
console.log("Login Successful", response);
// toast({ title: "Login Successful" });
} catch (error: any) {
console.error("Login Failed:", error);
// toast({ title: "Login Failed", description: error.message });
}
};

if go directly on /login and do authentication its working fine. but still my route are not protected and intialy not redirecting to my login page
Okay dude, your middleware is trashed. you are doing protection on all route.

make matcher to be on just '/someProtectedRoute'.

and then
  if (!response?.error) {
        router.push("/");
        router.refresh();
      }

This logic isn't quite right. if there are errors then maybe show the error to the user rather than redirecting them.
and if the login is success full then redirect the user to '/someProtectedRoute'. also you dont need router.refresh(). I do not understand the login why you are using it.
okay here is the my updated middleware file:
export { default } from "next-auth/middleware"; export const config = { matcher: [ "/", "/profile", "/settingsPage", "/approvals", "/enrolments", "/courses", "/students", ], };

and yes you are right the login function is not quit right i updated this but my problem still persists still my routed are not protected
Dude remove '/'