0

I have made this HOC to redirect unAuthenticated users:

export const ProtectRoute = ({ children }) => {
  const { isAuthenticated, isLoading } = useAuth();
  const router = useRouter()

  if (isLoading){
    return (<><Header/><h1>Loading</h1></>); 
  } 

  if (typeof window !== 'undefined') {
    if (!isAuthenticated && window.location.pathname !== '/emailLogin'){
      return router.push("/emailLogin")
    }
  }
  
  return children;
};

I have then wrapped my _app.js component with it:

     <AuthProvider>
        <ProtectRoute>
          <SearchProvider>
            <Component {...pageProps} />
          </SearchProvider>
        </ProtectRoute>
      </AuthProvider>

When redirecting i get the following error:

react-dom.development.js?61bb:20085 The above error occurred in the <ProtectRoute> 
component:

at ProtectRoute (webpack-internal:///./contexts/auth.js:721:25)
at AuthProvider (webpack-internal:///./contexts/auth.js:49:23)
at ToastProvider (webpack-internal:///./node_modules/react-toast-notifications/dist/ToastProvider.js:61:5)
at MyApp (webpack-internal:///./pages/_app.js:57:24)
at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:26:47)
at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:86:23)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:160:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:648:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:784:25)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

Any ideas as to why this is not working?

Jonatanbs
  • 223
  • 2
  • 9
  • something here might help you https://stackoverflow.com/questions/63251020/react-nextjs-protected-routes or https://medium.com/@eslamifard.ali/how-to-simply-create-a-private-route-in-next-js-38cab204a99c – danihazler Jul 27 '21 at 13:44
  • What's the error exactly? You're only showing us the stack trace. – juliomalves Jul 27 '21 at 15:19
  • Not sure.. this is the only thing showing in the console and the terminal is not showing any error. – Jonatanbs Jul 27 '21 at 15:47

1 Answers1

0

Fixed it. it's because i used return on router.push("...")

Jonatanbs
  • 223
  • 2
  • 9