I need to save a cookie for anonymous users in Drupal 8 when users visit the site for the first time, which will be used to display a message.

I can successfully save one using setcookie("FirstTimer", 1, strtotime('+1 year')); but I am sure Drupal 8 should have some alternatives.

I can also use the following code.

$user_is_first_timer = !isset($_COOKIE["Drupal_visitor_FirstTimer"]);

When I open it in Google Chrome, this works, but when I open it in incognito or in Firefox, there is no message. Somehow cached pages are being served.

The code is used in an implementation of hook_page_attachments().


As with Drupal 7, you can still use user_cookie_save(), in Drupal 8 and Drupal 9. There is just a method in a core class using that function: SystemController::compactPage().

Notice that the function accepts an array of values; each value will get its own cookie. Also, the function prepend Drupal.visitor. to the name of the value to make the cookie name; so, user_cookie_save(['myCookie' => 10]) will create a Drupal.visitor.myCookie cookie.

  • This saves the cookie, but somehow it doesn't depend on the browser!!.. Like I checked in chrome, the cookie is not set and the message is displayed, on refresh it's not; well and good. Now when I open it in Firefox I should get the message. But I don't. When I clear the cache the message shows up – Malabya Tewari May 26 '16 at 7:25
  • Cookies do depend from the browsers. If the second browser is not importing data from the first, it should not have any cookie. I cannot reproduce what you are saying in my test site. – kiamlaluno May 26 '16 at 7:32
  • Does Drupal core cache the cookies as well? drupal.org/developing/api/8/cache/contexts – Malabya Tewari May 26 '16 at 7:46
  • I don't think, or SystemController::compactPage() should disable the cache. – kiamlaluno May 26 '16 at 7:49
  • Is the cookies working for you? Can you somehow share your code? Here is what I am trying to do pastebin.com/AFg2xLWc The code in a Event Subscriber which is triggered for all page requests. More like hook_init in Drupal 7. – Malabya Tewari May 26 '16 at 9:49

Drupal 8 cookies can be set using ResponseHeaderBag from the Symfony\Component\HttpFoundation\Response object.

Set new cookie value

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;

$cookie = new Cookie('cookie_name', TRUE);
$response = new Response();
return $response;

Get cookies value


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.