Take care and use the right cache keys with the Craft Cache tag


« Back to overview

We love the craft {% cache %} tag in twig.

However, beware. If your template is using query GET or POST variables, the cache tag may show the wrong content!

This is because the parts after the url beginning with a ? (the 'query' parts) are NOT used in the cache key.
Typically, the query is used to filter content and get search result.

So, if you use {% cache %} on this url:

.../search?filter=products

and use the cache tag in your template, the results are stored in the cache for just '/search'. So the next user will view the wrong results when applying any filter.

Solution: use the cache tag with the full url as cache key:


{% cache using key craft.app.request.url for 120 seconds %}
     {% set filter = craft.app.request.queryParam('filter') %}
     {# do a query with filter #}
{% endcache %}