A Drupal JSON feed that invalidates itself
I keep seeing the same bug in custom Drupal endpoints: someone writes a controller that returns new JsonResponse($data), ships it, and then spends a week answering "why is the feed stale?" or, worse, "why did the feed show a draft?". A plain JsonResponse carries no cacheability metadata at all, so Drupal can't cache it correctly, and you end up either sprinkling max-age: 0 over it or caching it in some home-grown way that never invalidates. Here is the pattern I use instead: a CacheableJsonResponse that tells Drupal exactly what it depends on, so Dynamic Page Cache and any reverse proxy invalidate it for free.
The idea: the response declares its dependencies
Drupal\Core\Cache\CacheableJsonResponse extends Symfony's JsonResponse and uses CacheableResponseTrait. That trait gives you addCacheableDependency($dependency), which merges the cache tags, contexts and max-age of whatever you pass in. Entities are cacheable dependencies, so adding a node adds its node:123 tag. Save that node and the cached response is invalidated automatically.
A list needs one more tag. If a brand-new article is published, no existing node:ID tag changes, so the list must also depend on the entity type's list tag. EntityTypeInterface::getListCacheTags() returns that (node_list for nodes).
The controller
This returns the ten newest published articles as JSON. I collect everything in a CacheableMetadata object first, because the CacheableJsonResponse needs its data at construction time and I only know the dependencies after looping.
<?php
namespace Drupal\my_feed\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
/**
* Serves a cacheable JSON feed of recent articles.
*/
final class ArticleFeedController extends ControllerBase {
public function feed(): CacheableJsonResponse {
$node_type = $this->entityTypeManager()->getDefinition('node');
$storage = $this->entityTypeManager()->getStorage('node');
$ids = $storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'article')
->condition('status', 1)
->sort('created', 'DESC')
->range(0, 10)
->execute();
// A new article changes no existing node:ID tag, so depend on the list.
$metadata = (new CacheableMetadata())
->addCacheTags($node_type->getListCacheTags())
->addCacheContexts(['user.permissions']);
$items = [];
foreach ($storage->loadMultiple($ids) as $node) {
// Collect the URL's metadata instead of letting it leak.
$url = $node->toUrl('canonical', ['absolute' => TRUE])->toString(TRUE);
$items[] = [
'id' => (int) $node->id(),
'title' => $node->label(),
'url' => $url->getGeneratedUrl(),
'created' => (int) $node->getCreatedTime(),
];
$metadata->addCacheableDependency($node);
$metadata->addCacheableDependency($url);
}
$response = new CacheableJsonResponse(['items' => $items]);
$response->addCacheableDependency($metadata);
return $response;
}
}
The route
my_feed.articles:
path: '/api/articles'
defaults:
_controller: '\Drupal\my_feed\Controller\ArticleFeedController::feed'
methods: [GET]
requirements:
_permission: 'access content'
Why each piece is there
accessCheck(TRUE)is mandatory on entity queries in current Drupal; I want node access applied, not bypassed.user.permissionscontext is there because the result can differ by what a user is allowed to view. Without it, one user's cached result could be served to another. If your site has node access modules, check which contexts they add.toString(TRUE)returns aGeneratedUrlobject carrying its own bubbleable metadata. PlaintoString()in a controller that isn't inside a render context can leave that metadata unaccounted for.- The list tag is what makes a freshly published article appear immediately.
The gotcha I would watch for: anything you read to build the payload is a dependency. If you also put an author name or a taxonomy term label into the JSON, add that entity too, or you will serve a stale name until the node itself is re-saved. I trace it by asking, for every value in the array, "what edit would change this?" and then confirming a tag covers it. This is overkill for an endpoint that must be live per request, where you should say so explicitly with max-age 0, but for read-mostly feeds it replaces hand-rolled cache code with about ten lines of metadata. I traced the code through by hand rather than running it, so run it against your own node access setup before relying on it.