drupal_set_message for anonymous user I am having hard time displaying drupal message for anonymous users. My scenario is, I need to display message if there is certain query string and remove the query string with message. I am using following code but without success. I also tried with session variable without success. 

 if(isset($_GET['action']) &amp;&amp; $_GET['action'] === 'loggedoff'){
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    \Drupal::logger('vrpboostrap')-&gt;notice('query parameter has value loggedoff');
    $url = \Drupal::service('path.current')-&gt;getPath();
    $alias = \Drupal::service('path.alias_manager')-&gt;getAliasByPath($url);
    $alias = strtok($alias, '&amp;');
    header('Location: '. base_path() . $alias);
    exit;
  }


With Session variable, I tried with: 

if (isset($_GET['action']) &amp;&amp; $_GET['action'] === 'loggedoff') {
    $_SESSION['vrp_action'] = 'loggedoff';
    $url = \Drupal::service('path.current')-&gt;getPath();
    $alias = \Drupal::service('path.alias_manager')-&gt;getAliasByPath($url);
    $alias = strtok($alias, '&amp;');
    header('Location: ' . $url);
    exit;
  }
  if (isset($_SESSION['vrp_action']) &amp;&amp; $_SESSION['vrp_action'] === 'loggedoff') {
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    session_unset('vrp_action');
  }


Can you guys advise me what am I doing wrong here and to display message for anonymous users?
The fact that you use header() and exit is most likely the problem.

You need to use response objects that you return to properly terminate the request and write the session data.

You can't do this anywhere, I'd recommend implement a Request event subscriber. \Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber is a simple example for this:

class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event-&gt;getRequest();
    // Get the requested path minus the base path.
    $path = $request-&gt;getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request-&gt;getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event-&gt;setResponse(new CacheableRedirectResponse($request-&gt;getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}


And then register that in yourmodule.services.yml:

redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }