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' => 0];

    if (some value not in session) {
        $response = new TrustedRedirectResponse($some_url);
        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.


1 Answer 1


I just discovered that it's related to the TrustedRedirectResponse.

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

  • Yes, and you can simply return the response return new RedirectResponse($some_url);, the Form API knows what to do with it.
    – 4uk4
    Feb 3, 2019 at 19:37
  • Thanks @4k4 I also now see that if I really need a TrustedRedirectResponse for an external url then it's $response->getCacheableMetadata()->setCacheMaxAge(0) to disable caching, not $response->setMaxAge(0) as I was trying. That only sets an http header.
    – tetranz
    Feb 3, 2019 at 21:04
  • Redirect response also gets cached with Internal dynamic page cache module. Jun 19, 2020 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.