Route Guard
Guest Guard
For NextJS

How to work ?

Sometimes you may want to make certain routes, such as /register, /login, etc., only accessible to users who are not authenticated. You can use the GuestGuard component to direct users to a specific route/page (/dashboard) by using it.

GuestGuard.jsx

_18
"use client";
_18
_18
import { useRouter } from "next/navigation";
_18
import { useEffect } from "react";
_18
import useAuth from "hooks/useAuth";
_18
_18
const GuestGuard = ({ children }) => {
_18
const router = useRouter();
_18
const { isAuthenticated } = useAuth();
_18
_18
useEffect(() => {
_18
if (isAuthenticated) router.replace("/dashboard");
_18
}, [isAuthenticated]);
_18
_18
return <>{children}</>;
_18
};
_18
_18
export default GuestGuard;

How to use it ?

layout.jsx

_10
import { GuestGuard } from "components/auth";
_10
_10
const AuthLayout = ({ children }) => {
_10
return <GuestGuard>{children}</GuestGuard>;
_10
};
_10
_10
export default AuthLayout;