How do I avoid caching a redirect response from a form? I have a Drupal 8 form used by authenticated users which sometimes needs to redirect based on the presence of absence of something in session. I don't want the redirect to be cached.

My form is displayed directly with a route. i.e., the route has a _form default pointing to the form class.

My buildForm method starts like this:

public function buildForm(array $form, FormStateInterface $form_state) 
{
    $form['#cache'] = ['max-age' =&gt; 0];

    if (some value not in session) {
        $response = new TrustedRedirectResponse($some_url);
        $response-&gt;setMaxAge(0);
        throw new EnforcedResponseException($response);  
    }

    // build the form.
}


I have not been able to avoid the redirect response being cached. It redirects as expected if the session variable does not exist but continues to redirect next time when the session variable does exist.

Users are authenticated so it is the dynamic page cache. drush cr or uninstalling the dynamic page cache "fixes" the problem.
I just discovered that it's related to the TrustedRedirectResponse.

A standard Symfony\Component\HttpFoundation\RedirectResponse is not cached.