Caching page depending on user roles

Hi,

I’m working on a project with a collection of ~1500 images, displayed on the homepage depending on the 4 following users roles:

  • general1: see all images (default)
  • limited2: see only images with Limited 2 access level or above
  • limited3: see only images with Limited 3 access level or above
  • limited4: see only images with Limited 4 access level

site/collections/images.php

<?php

return function ($kirby, $site) {
	$images = $site->find('collection')->children()->listed()->images();

	// Filter images depending on users roles
	if ($user = $kirby->user()) {
		if ($user->role()->id() === 'limited2') {
			$images = $images->filterBy('access', '*=', 'limited');
		}
		elseif ($user->role()->id() === 'limited3') {
			$images = $images->filterBy('access', 'in', ['limited3', 'limited4']);
		}
		elseif ($user->role()->id() === 'limited4') {
			$images = $images->filterBy('access', 'limited4');
		}
	}

	return $images;
};

I would like to be able to cache the page to reduce its load time, but I can’t because its content depends on user roles. What are the possible solutions? Is there a way to get like 4 different cached versions of a page?

Private responses (responses that depend on the logged-in user or cookies) are never cached by Kirby to protect against accidental leaks of personal data. So as soon as you call $kirby->user() somewhere during page rendering (directly or indirectly), the pages cache is disabled.

What you could do is to implement a custom route for the homepage that calls page('home')->render() and caches the result in a custom cache.