I am developing an app with nextjs nodejs and express. I made that if a user is not logged in and tries to hit /
it is automatically redirected to /login
.
The thing is that I am having issues doing the same the other way. If a user is logged in and tries to hit /login
it should redirect him automatically to /
I tried doing this but in between the redirection I am able to see the content of the login page for 1 or 2 seconds before the redirection, but instead I should not see the content before redirecting to /
.
This is my page.container.tsx
"use client"
import { FC, PropsWithChildren, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import useAuthContext from "@/contexts/authContext";
const IndexPageContainer: FC<PropsWithChildren> = ({children}: PropsWithChildren) => {
const router = useRouter();
const { authToken } = useAuthContext();
useEffect(() => {
if (!authToken) {
router.push('/login');
} else {
router.push('/')
}
enter code here
}, [authToken, router]);
return authToken ? children : null;
}
export default IndexPageContainer;
src/app/layout.tsx
import IndexPageContainer from './(main)/page.container';
import './globals.css'
import { AuthProvider } from '@/contexts/authContext';
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className={``}>
<body className="flex">
<AuthProvider>
<IndexPageContainer>
{children}
</IndexPageContainer>
</AuthProvider>
</body>
</html>
);
}
src/app/(main)/login/page.tsx
import LoginForm from "@/components/auth/LoginForm"
import IndexPageContainer from "../(main)/page.container";
const LoginPage = () => {
return <IndexPageContainer>
<div className="flex items-center flex-col w-full mx-auto py-36">
<div className="flex items-center justify-center mb-36 w-full">
<h2 className="font-bold text-white text-2xl">Top Value Brands</h2>
</div>
<LoginForm/>
</div>
</IndexPageContainer>
}
export default LoginPage;
How can I make to automatically redirect to /
if I try to go to login
while being already logged in?