I am doing a routing based on the role of the user in nextjs. I did one hook which returnes true or false if a user is allowed to navigate in a route. I want to intercept that into _app.tsx file so I did the following thing:
_app.tsx
const App: React.FC<{
Component: React.FC;
pageProps: Record<string, any>;
}> = ({ Component, pageProps }) => {
const router = useRouter();
const user =
typeof localStorage !== 'undefined'
? (JSON.parse(localStorage.getItem('user') ?? 'null') as
| User
| { role: undefined })
: null;
//useRouteProvider returns true/false
const isUserAllowedOnRoute = useRouteProvider(router.pathname, user?.role);
if (!isUserAllowedOnRoute) {
window.location.replace('/');
// I also tried router.push('/') and Router.push('/') but I can't use that into this file.
}
return (
//...
);
};
export default App;
In this case the error is ReferenceError: window is not defined
Based on the value of isUserAllowedOnRoute
, how can I redirect to a certain route from here?