Twig/Drupal caching and dynamic variables
My understanding is that this doesn't vary on the same URL, so both page_cache and dynamic_page_cache should be fine. However, each node is also cached on its own, a and that's your problem here.

As 4k4 said in the comment, you should be able to vary the cache with this: $variables['#cache']['contexts'][] = 'url'.

That's rather problematic however, because it means that every node needs to be cached differently on every page, which results in a huge amount of variations that fill up your cache tables.

You could define your own cache context for whether you are on the node page of a given node. Core actually should provide a cache context for that, since it has a similar problem when you'd e.g. use the default view mode somewhere else than on the node/N page. But it doesn't, there's an open issue for that.

As mentioned, the easiest fix is probably to use JS for this.