I have a multilingual site where I use in most of my custom modules (.module files) and in the mycustomtheme.theme file these lines of code : \Drupal::languageManager()->getCurrentLanguage()->getId();

\Drupal::service('domain.negotiator')->getActiveId(); I want to install Varnish on my site, and I know that I can specify some URLs not to be cached like for instance I specified the path of a custom controller where \Drupal::languageManager()->getCurrentLanguage()->getId(); is used so that the page related to this controller is not cached. However, I don't know what to do for all the .module files where I used this line of code. Does this function ->getCurrentLanguage()->getId(); have a specific path so that I can specify its path to be ignored by varnish ? PS: this is important because some features differ from one user to another depending on the website's language.


For anonymous traffic not getCurrentLanguage()->getId() is the problem, it's the language detection method. Browser based is not recommended. For cache performance it's a better idea to redirect to the path based language detection method after you have determined the browser language, for example with the module Redirect. For this you need to configure a language prefix for all languages.

  • thank you for your answer. can you please elaborate a bit? Basically i use this expression not to redirect user, but just to detect his language. I already have a language prefix for example /fr for french. but in my customtheme.theme I use it for example in hook_page_attachments_alter or in custom module to send a specific block based on the website language.. I use it a lot and i'm afraid, if the page is cached, the n all of the users will see the same block in the same language..
    – user105449
    Oct 5 at 17:32
  • As said, this is not the problem. Everything on a Drupal page is translatable, it doesn't matter if you add another translatable block. Of course you can't redirect from a hook or block. You need an event subscriber. The module Redirect would be a no-code solution because it has already an event subscriber redirecting to the canonical path of a page. This includes the language prefix. The prefix needs to be configured for all languages, also the site's default language, and the priority in the detection list has to be higher than the browser detection.
    – 4k4
    Oct 5 at 18:42

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.