Clearing the render cache after being programmatically logged in This issue is on a Drupal 8 site.  I have no reason to think it would behave any different on Drupal 9.
We have a scenario where we are having trouble with caching of a custom block.
This block replicates the behaviour of the Login block in that it checks for an authentication state and presents either the user.login or user.logout route.
This looks to be working.
We also have a login state happening where a user account can be &quot;Not Quite Logged In&quot; (NQLI). We are extending Terms with an IP field and adding an IP Login User user reference field.  When a user hits the site and they are not logged in we check if their IP matches one mentioned on the Terms and if one matches the referenced user is programatically logged in.
When a NQLI user is logged in the Login block still presents a &quot;Log in&quot; link. This is the desired behaviour so the user can still access the login page to log in as an actual personal account.
This is working also.
When a user has accessed the site from a known IP and is logged in as a NQLI user, clicks the &quot;Log in&quot; link, logs in as their own account and is redirected back to the page they came from they are successfully logged in as that personal account.
This process works.
What doesn't work is that the &quot;Log in&quot; menu item is still present in that block on this page.  If you click off to any other page the &quot;My account&quot; and &quot;Log out&quot; links are there as expected.  If you click back to the page you logged in from it still holds the &quot;Log in&quot; link.
We've tried clearing the cache with \Drupal::service('cache.render')-&gt;invalidateAll(); in hook_user_login() and hook_preprocess_html().
This is one of my first Drupal 8+ projects. I've been working with Drupal since 4.6 and am very much feeling like a junior dev once again. I'm hoping that there is an obvious place or process to do this that I've just not been able to find. My google-fu has reached its limit on this one.
You need to add cache contexts to your block. Cache contexts tell Drupal that the block needs to be cached differently for different circumstances. In your case, whether or not the user is logged in. you can read more about it here: https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts