Route Guard
Auth Guard
For NextJS

How to work ?

A private route can be protected using this AuthGuard component. It decides whether to permit navigation to a requested route.

AuthGuard.jsx

_23
"use client";
_23
_23
import { useState, useEffect } from "react";
_23
import { usePathname, useRouter } from "next/navigation";
_23
import useAuth from "hooks/useAuth";
_23
_23
const AuthGuard = ({ children }) => {
_23
const router = useRouter();
_23
const pathname = usePathname();
_23
const { isAuthenticated } = useAuth();
_23
const [isLoggedIn, setIsLoggedIn] = useState(false);
_23
_23
useEffect(() => {
_23
if (!isAuthenticated) router.replace("/login");
_23
else setIsLoggedIn(true);
_23
}, [isAuthenticated]);
_23
_23
if (isLoggedIn) return <>{children}</>;
_23
_23
return <Loading />;
_23
};
_23
_23
export default AuthGuard;

How to use it ?

layout.jsx

_12
import { AuthGuard } from "components/auth";
_12
import DashboardLayout from "layouts/dashboard/DashboardLayout";
_12
_12
const Layout = ({ children }) => {
_12
return (
_12
<AuthGuard>
_12
<DashboardLayout>{children}</DashboardLayout>
_12
</AuthGuard>
_12
);
_12
};
_12
_12
export default Layout;