I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side:
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await auth();
return (
...
<NavBar authenticated={!!session} />
...
);
}
export default function NavBar({ authenticated }: { authenticated: boolean }) {
return (
...
{authenticated ? (
<form action={logOut}>
<button>
Sign out
</button>
</form>
) : (
<Link
href="/login"
>
Sign in
</Link>
)}
...
);
}
export default function LoginPage() {
const [errorMessage, dispatch] = useFormState(authenticate, undefined);
const router = useRouter();
const { pending } = useFormStatus();
if (errorMessage === "ok") {
router.push("/");
}
return (
<LoginForm />
);
}
However, I encountered an issue where even after successful login, the navbar does not refresh and still shows "Sign in". What is the best approach to manage authentication state on the client side?
To solve this problem, I replaced router.push("/")
with
window.location.href = ("/")
after the execution of singUp
.