UNPKG

@auth0/nextjs-auth0

Version:
38 lines (37 loc) 1.69 kB
"use client"; import React, { useEffect } from "react"; import { useRouter as usePagesRouter } from "next/compat/router.js"; import { usePathname } from "next/navigation.js"; import { normalizeWithBasePath } from "../../utils/pathUtils.js"; import { useUser } from "../hooks/use-user.js"; const defaultOnRedirecting = () => React.createElement(React.Fragment, null); const defaultOnError = () => React.createElement(React.Fragment, null); export const withPageAuthRequired = (Component, options = {}) => { return function WithPageAuthRequired(props) { const { returnTo, onRedirecting = defaultOnRedirecting, onError = defaultOnError } = options; const loginUrl = normalizeWithBasePath(process.env.NEXT_PUBLIC_LOGIN_ROUTE || "/auth/login"); const { user, error, isLoading } = useUser(); const pagesRouter = usePagesRouter(); const pathname = usePathname(); useEffect(() => { if (pagesRouter && !pagesRouter.isReady) return; if ((user && !error) || isLoading) return; let returnToPath; if (!returnTo) { const currentLocation = window.location; returnToPath = pathname + currentLocation.search + currentLocation.hash; } else { returnToPath = returnTo; } window.location.assign(`${loginUrl}?returnTo=${encodeURIComponent(returnToPath)}`); }, [user, error, isLoading]); if (error) return onError(error); if (user) return React.createElement(Component, { user: user, ...props }); return onRedirecting(); }; };