I want to remove all libraries of modules & themes, except those from modules/themes that are defined by me. This should only be done for anonymous users. All libraries should be served to authenticated users.
I'm adding the user.roles cache context in the html preprocess hook and remove all library definitions that are not desired:
/**
* Implements hook_preprocess_html().
*/
function mytheme_preprocess_html(array &$variables) {
$variables['page']['#cache']['contexts'][] = 'user.roles';
}
/**
* Implements hook_library_info_alter().
*/
function mytheme_library_info_alter(array &$libraries, $module) {
/* Remove all libraries that are not needed.
Only remove them for anonymous users, since a lot of libraries are required for the admin interface to work. */
$allowed_modules_with_libraries = [
'mytheme',
'google_tag',
'my_custom_module',
];
if (!in_array($module, $allowed_modules_with_libraries) && !Drupal::currentUser()->isAuthenticated()) {
$libraries = [];
}
}
My problem is, that the attached libraries are not completely separated by user role cache context:
My test workflow:
- Clear all caches
- Requesting page as authenticated user
- Contrib assets in browser sources panel:
This is as expected.
- Requesting same page as anonymous user
- Contrib assets in browser sources panel:
This is not as expected, nothing should be present here.
The other way around:
- Clear all caches
- Requesting page as anonymous user
- No contrib assets are displayed browser sources panel.
This is as expected.
- Requesting same page as authenticated user
- Assets in browser sources panel:
This is not as expected, paragraphs and webform assets are missing.
The x-drupal-cache-contexts HTTP response header content: languages:language_content languages:language_interface languages:language_url route session theme timezone url.path url.query_args user
The user
cache context is there, shouldn't the response be cached by user (including the role) then?
I tried doing this by using hook_page_attachments_alter, but not all libraries that are attached to the response are listed there. I'm not sure if changing the library definitions with hook_library_info_alter is the right approach. Since I don't want to change the libraries. I just want to detach them from the response.
The page_cache
and dynamic_page_cache
modules are enabled.