Creating a custom Drupal cache context based on user role
Cache contexts in Drupal describe the circumstances under which a cached representation is valid. A page can have separate public, standard-member and partner versions while keeping the same URL. For a publisher serving clients from Sydney, Melbourne and Brisbane, that distinction allows calls to action and supporting content to change without rebuilding unrelated pages on every request.
Drupal core already provides user.roles, which is the right starting point when every assigned role should influence cached output. A custom context is useful when operational roles need to be translated into a smaller publishing or membership dimension. For example, a professional association could use member, premium_member and partner_editor internally while caching only standard, premium and partner segments.
A custom context should answer one precise question: which role-derived segment does this visitor occupy? It should not decide whether the visitor may view an entity. That remains the job of route access, permissions and entity field access. The context only prevents a response built for one segment from being reused for another.
In Drupal 10 and 11, the context can be a service tagged with cache.context and attached to a render array or cacheable service. Its context value must be deterministic: the same role should always produce the same value, and the number of possible values should remain small. That discipline matters on busy Australian sites where teams commonly move between Melbourne development, Brisbane testing and Sydney production environments.
Why role-based cache variation matters
Cache variation begins when a renderable declares the contexts that affect its output. Drupal then includes those values in the relevant cache key. A membership banner can consequently have a public version for anonymous visitors and a separate version for members without mixing the two responses during reuse.
Adding user.roles to cached output is straightforward, but every assigned role can create another variation. Administrative roles, editorial roles and commercial roles may also exist in combinations. A custom context can map those operational roles to a controlled set of segments, reducing unnecessary variation while preserving the distinctions that the page actually needs.
Cache metadata has no authority over access control. Permissions and entity access must still prevent an unauthorised user from receiving protected data. For an Australian organisation handling personal information, the Privacy Act 1988 and Australian Privacy Principles also make it sensible to keep sensitive details out of cache labels and to document why a membership segment exists. Role names and segment values should identify a category, not disclose account-specific personal information.
Designing a stable role context
Start with stable Drupal role IDs rather than human-readable labels. A label such as “Premium Member” can be translated or edited for different audiences, while the machine-readable ID remains suitable for code and configuration. Create the roles explicitly, assign them through a controlled workflow and document which roles map to each cached segment.
Choose a small vocabulary for the context. The example context will produce public, standard, premium, partner or restricted. If a visitor holds several roles, apply an explicit priority rather than depending on the order returned by Drupal. This prevents the cache key from changing when the assignment order changes and keeps the number of stored variations predictable.
Keep the context’s scope narrow. It should describe a role-derived segment, not every property of the current account. Content that differs for each person needs a user-aware context and appropriate access checks. When a role is removed, the next request receives a different context value and therefore a different cache key; the obsolete variation can remain stored until it expires or is purged.
Implementing the context service
Create a class under the module’s src/Cache/Context directory. Extending CalculatedCacheContext provides the interface Drupal expects, while the current user service supplies the roles used for calculation.
<?php
namespace Drupal\custom_role\Cache\Context;
use Drupal\Core\Cache\Context\CalculatedCacheContext;
use Drupal\Core\Session\AccountProxyInterface;
final class MembershipSegmentCacheContext extends CalculatedCacheContext {
protected AccountProxyInterface $currentUser;
public function __construct(AccountProxyInterface $current_user) {
$this->currentUser = $current_user;
}
public function getContext() {
if (!isset($this->context)) {
$roles = $this->currentUser->getRoles();
if ($this->currentUser->isAnonymous()) {
$this->context = 'public';
}
elseif (in_array('partner_editor', $roles, TRUE)) {
$this->context = 'partner';
}
elseif (in_array('premium_member', $roles, TRUE)) {
$this->context = 'premium';
}
elseif (in_array('member', $roles, TRUE)) {
$this->context = 'standard';
}
else {
$this->context = 'restricted';
}
}
return $this->context;
}
public function getCacheKey() {
return $this->getContext();
}
}
The partner role deliberately takes priority because a partner editor may also hold a premium membership. The restricted fallback fails closed for authenticated accounts without a recognised role. No user ID appears in the context, so accounts within the same segment can share a cached variation without becoming individually cacheable.
Register the class as a tagged service in custom_role.services.yml:
services:
cache_context.custom_role.membership_segment:
class: Drupal\custom_role\Cache\Context\MembershipSegmentCacheContext
arguments:
- '@current_user'
tags:
- cache.context
After enabling the module, rebuild Drupal’s service container and caches so the tagged service is discovered. The service ID exposes the context as custom_role.membership_segment, matching the name used by render arrays and cacheable services.
Applying the context to cached output
Attach the context wherever the affected renderable is assembled. For a block with a fifteen-minute lifetime, the metadata can be added like this:
$build['#cache']['max-age'] = 900;
$build['#cache']['contexts'][] = 'custom_role.membership_segment';
A service implementing CacheableRenderArray should return the same string from its getCacheContexts() method. If a complete response contains authenticated content, also apply Drupal’s user.roles context or an equivalent private-cache response policy. A custom context alone should not be treated as protection against shared reverse-proxy caching.
An origin hosted in a Sydney or Melbourne cloud region may sit behind edge caches in other locations, so administrators should inspect Cache-Control, cache tags and purge behaviour rather than assuming geography separates responses. Drupal can calculate the correct variation internally, but the outer caching layer must honour that metadata.
When the cached block is progressively enhanced, JavaScript resource loading remains a separate concern from server-side variation. JavaScript may adjust an interface after the response arrives, but it must not reveal protected information that the server deliberately omitted. Secure data should remain behind Drupal’s session, permission and entity-access checks.
Operational safeguards and deployment checks
Test anonymous visitors, standard members, premium members, partner editors and users holding several roles. Also test removing a role and verify that the next response uses the new segment. Include checks for expiry labels and dates, especially where Australian sites display DD/MM/YYYY and use Australia/Sydney or Australia/Brisbane. Daylight-saving transitions can reveal errors if cached content contains a time calculated from the wrong offset.
Deploy role definitions through version-controlled configuration rather than making production assignments manually. This approach suits .com.au organisations and the Australian Drupal agency market, where staging and production environments must remain reproducible. When role mappings or segment names change, rebuild Drupal’s caches and purge affected CDN objects so stale variations cannot be selected after deployment.
Several safeguards keep the implementation reliable:
- Limit context values to a small, documented set of business segments.
- Give multi-role users an explicit mapping priority.
- Keep display variation separate from permission and entity access checks.
- Automate role-combination tests in continuous integration.
- Rebuild and purge caches whenever segment definitions change.
The practical differences can be summarised as follows:
| Requirement | Core user.roles |
Custom role context | Preferred approach |
|---|---|---|---|
| Every assigned role affects cached output | Automatic | Requires explicit mapping | Core user.roles |
| Several roles represent one business tier | Produces role combinations | Produces one controlled segment | Custom role context |
| Display a role-based teaser or price label | Built in | Fully configurable | Custom context when normalisation matters |
| Enforce access to protected content | Not responsible | Not responsible | Permissions and entity access |
| Show content unique to each account | Insufficient | Insufficient | User-aware caching with access checks |
A completed implementation separates role-based presentation from authorisation while giving Drupal a predictable cache key. The result is controlled variation for public, member and partner audiences without weakening Drupal’s access-control model.