I'm implementing an authentication flow which authenticated users are detected when a httpOnly cookie is present (server side).
I'm trying to redirect unauthenticated users on protected pages, so i created a react HOC:
const isBrowser = () => typeof window !== "undefined";
export const withAuth = (WrapperComponent: React.ComponentType) => {
const Wrapper = (props: any) => {
const { loading, authenticated } = useAuth();
const router = useRouter();
if (!loading && !authenticated && isBrowser()) {
router.push("/auth/login");
return null;
}
return <WrapperComponent {...props} />;
};
return Wrapper;
};
The code works fine in client-side redirects, but what I'm trying to do is redirect users before they reach to client, I tried getInitialProps
but seems like it opts out the entire app from automatic static optimization and getServerSideProps
are not supported in HOCs, and if i want to use getServerSideProps
i have to do it in all protected pages, is there any alternative solution to handle protected pages without having to use getInitialProps
or getServerSideProps
on every page?
P.s: In case you need to know how the auth cookie works:
The useAuth
is a custom context i created which works like this:
- On Initial load of a page it sends a http request to
/api/user/
if this request contains a refresh token cookie the server will check for validity of the token and if it's valid it returns user data and an accessToken which then they are saved using react hooks and based those values theauthenticated
variable which you see in the example turns true or false - Upon absence of
accessToken
anduser
data the above step will repeat silently and if refresh token is valid a new accessToken and user is fetched and stored otherwiseauthenticated
will be set to false and user data and accessToken will be empty