Here is a very common use case – User pages such as dashboard, profile etc…
The code below works 70% of the time in pages router. I say 70% because sometimes logged in users need to click twice to get to the /dashboard router possibly because it takes time to read the logged in or not cookie?
How can this be implemented in the APP router and make it work 100% of the time? I will need to use ‘use client’ when I move this to APP router so is there a better alternative to getInitailProps that would work and is cookies the only way ?
Dashboard.getInitialProps = ({ req, res }) => {
const isLoggedIn = getCookies(req).cookies.loggedIn;
if (isLoggedIn == "true") {
return {loggedIn: true};
}
else {
if (res) {
// We're on the server.
res.writeHead(307, { Location: '/login' });
res.end();
} else {
// We're on the client.
Router.push('/login');
}
}
}
On the Dashboard page, I do have access to user but if I dont use getInitialProps, it always redirects because user gets time to be available.
export default function Dashboard({data}) {
const [user, { mutate }] = useCurrentUser();