After a lot of searching for several hours, I have the following code to redirect from a user profile page if not logged in.

NOTE: Simply showing a not authorized page is easy but its the redirect thats messing things up.

The code does the job of redirecting when user is not logged in.

```
const Dashboard = () => {  
  const [user, { mutate }] = useCurrentUser();
  const router = useRouter();
  useEffect(() => {
    // redirect to login if user is not authenticated
    if (!user) router.push('/login');
  }, [user]);
...

```

The **problem** is when a **user is logged in** and directly goes to /user/dashboard route, for a split second, user is undefined may be so it redirects to login. When it gets to login, it finds that user is authenticated so redirects to home page because I am redirecting a logged in user to home page.

How to prevent that split second of "not a user" status when page is first loading?

I tried -

1. getInitialProps
2. getServerSideProps - Cant use router because next router can only be used on client side
3. componentDidMount - UseEffectI tried above is the equivalent correct?

Edit: Based on answer below, I tried this but still directly takes user to login first. I am using react cookies and I do see loggedIn cookie as true when user is logged in and its not set when user is not logged in.

```
Dashboard.getInitialProps = ({ req, res }) => {
  console.log(req.headers.cookie)
  var get_cookies = function(request) {
    var cookies = {};
    request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
      var parts = cookie.match(/(.*?)=(.*)$/)
      cookies[ parts[1].trim() ] = (parts[2] || '').trim();
    });
    return cookies;
  };

  //console.log(get_cookies(req)['loggedIn']);

  if (get_cookies(req)['loggedIn'] == true) {
    console.log("entered logged in")
    return {loggedIn: true};
  }
  else {
    console.log("entered not logged in")// can see this on server console log
  // User is not logged in, redirect.
  if (res) {
      // We're on the server.
      res.writeHead(301, { Location: '/login' });
      res.end();
    } else {
      // We're on the client.
      Router.push('/login');
    }
  }
}

```