Stop Caching In Drupal 8 Custom Module Block

I created a custom module for next/previous posts since there isn’t one out there for D8. And even if one is out there, it wouldn’t fit our needs since we have different taxonomies and different blogs.

I ran into this caching of blocks issue I had when I developed the flex_carousel module for D8 and it was super annoying. I worked around it using JQuery. I wasn’t happy about that solution.

Now I ran into this issue again; and this time it cannot be JSed around. It needs to not cache.

I developed the module to display next/previous posts when you’re on a blog content type. It works fine if you’re always on the same node but you’re always not on the same node so in other words, it doesn’t work. It keeps the same next/previous posts no matter what node you’re on.

Caching needs to be turned off for this block!
Add this simple function (method) to your block class. Looks something like…

class NextPreviousPost extends BlockBase {
	public function build() {
		/* your build code here */

	 * {@inheritdoc}
	public function getCacheMaxAge() {
		return 0;

It’s that simple! It changed my life.

Leave a Reply

Your email address will not be published.