Skip to content

Instantly share code, notes, and snippets.

@azeezat
Last active March 26, 2022 08:22
Show Gist options
  • Save azeezat/32aa126779007b65b2d17bda39fe4d0a to your computer and use it in GitHub Desktop.
Save azeezat/32aa126779007b65b2d17bda39fe4d0a to your computer and use it in GitHub Desktop.
import { appRoutes } from "../constants";
import { useAuthContext } from "../contexts";
//check if you are on the client (browser) or server
const isBrowser = () => typeof window !== "undefined";
const ProtectedRoute = ({ router, children }) => {
//Identify authenticated user
const { user } = useAuthContext();
const isAuthenticated = user.isLoggedIn;
let unprotectedRoutes = [
appRoutes.LOGIN_PAGE,
appRoutes.FORGOT_PASSWORD,
appRoutes.RESET_PASSWORD,
appRoutes.EMAIL_SENT,
appRoutes.VERIFY_EMAIL,
appRoutes.NEWS_FEED_PAGE,
appRoutes.CONTENT_DETAILS_PAGE,
appRoutes.ABOUT_US_PAGE,
];
/**
* @var pathIsProtected Checks if path exists in the unprotectedRoutes routes array
*/
let pathIsProtected = unprotectedRoutes.indexOf(router.pathname) === -1;
if (isBrowser() && !isAuthenticated && pathIsProtected) {
router.push(appRoutes.LOGIN_PAGE);
}
return children;
};
export default ProtectedRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment