\Drupal::currentUser() returns information about the anonymous user, even though I am logged in I'am trying to check whether a user is logged-in or not; with \Drupal::currentUser()-&gt;id() I am getting the user ID for the anonymous user (i.e. 0), even though I'm logged in.

How can I resolve this?

I'm just calling this function in the .module file, and it is not run from cron. I am using the following code.

use Drupal\Core\Session\UserSession;
use Drupal\Core\Session\AccountInterface;

$user = \Drupal::currentUser();
if ($user-&gt;isAuthenticated()) {
  echo 'logged-in';
}
else {
  echo 'guest';
}
To determine if a user is logged-in (authenticated), it would be best to use:

\Drupal::currentUser()-&gt;isAuthenticated()