Router Not Redirecting
Unanswered
Cattle Egret posted this in #help-forum
Cattle EgretOP
The router is not redirecting the user to the destination
Here's the code i am using
The console.log statement inside it runs but don't redirect
Here's the code i am using
"use client";
import Loading from "@/components/Loading";
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Login() {
const { data: session, status } = useSession();
const router = useRouter();
useEffect(() => {
if (status == "authenticated" && session) {
console.log("Authenticated");
router.push("/dashboard");
} else if (status != "loading" && !session) {
console.log("Not authenticated");
signIn("discord", { callbackUrl: "/dashboard" });
}
}, [status, session]);
return <Loading />;
}
The console.log statement inside it runs but don't redirect
10 Replies
Do you see anything in the console
@Anay-208 | Ping in replies Do you see anything in the console
Cattle EgretOP
nah, it only executes every code inside it but just don't redirect
@Cattle Egret nah, it only executes every code inside it but just don't redirect
Its probably because router isn't initialised, can you try adding it in the dependency array?
@Cattle Egret The router is not redirecting the user to the destination
Here's the code i am using
tsx
"use client";
import Loading from "@/components/Loading";
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Login() {
const { data: session, status } = useSession();
const router = useRouter();
useEffect(() => {
if (status == "authenticated" && session) {
console.log("Authenticated");
router.push("/dashboard");
} else if (status != "loading" && !session) {
console.log("Not authenticated");
signIn("discord", { callbackUrl: "/dashboard" });
}
}, [status, session]);
return <Loading />;
}
The console.log statement inside it runs but don't redirect
You are running this as soon as page loads, when the router isn't initialised and none of the functionw would work.
Instead, set useEffect to this.
Instead, set useEffect to this.
useEffect(() => {
if(!router) return;
if (status == "authenticated" && session) {
console.log("Authenticated");
router.push("/dashboard");
} else if (status != "loading" && !session) {
console.log("Not authenticated");
signIn("discord", { callbackUrl: "/dashboard" });
}
}, [status, session, router]);
Cattle EgretOP
ah wait, it looks like this is error of middleware, it redirecting user back to login as error occured during login