Using LocalRedirectResponse with "<front>" URL in controller results in LogicException

Created on 24 July 2024, about 2 months ago
Updated 25 July 2024, about 1 month ago

Problem/Motivation

When I tried to create a redirection route in a contrib module, 💬 How to use with for tfa (two factor authentication aka 2fa) Needs review , using LocalRedirectResponse I faced the
"LogicException The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Ensure you are not rendering content too early. Returned object class: LocalRedirectResponse".

Steps to reproduce

  • Create a module with the following route and controller:

    routing.yml

    custom.redirect:
      path: '/custom/redirect'
      defaults:
        _title: 'Redirect'
        _controller: \Drupal\module\Controller\RedirectController::redirect
      requirements:
        _access: 'TRUE'
    

    controller

    final class RedirectController extends ControllerBase {
      public function redirectToServiceProvider(): RedirectResponse {
          return new LocalRedirectResponse(
            Url::fromRoute('<front>')->toString()
         );
      }
    }
    
  • Navigate to /custom/redirect
  • Observe LogicException

Using RedirectResponse instead of LocalRedirectResponse works as expected.

Proposed resolution

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

🐛 Bug report
Status

Active

Version

11.0 🔥

Component
Base 

Last updated 28 minutes ago

Created by

🇳🇿New Zealand RoSk0 Wellington

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @RoSk0
  • Try this code if it works for you.

    use Drupal\big_pipe\Render\Placeholder\BigPipeStrategy;
       use Drupal\Core\Cache\CacheableMetadata;
       use Drupal\Core\Routing\LocalRedirectResponse;
    
        $response = new LocalRedirectResponse(Url::fromRoute('<front>')->toString());
        $response->addCacheableDependency((new CacheableMetadata())->addCacheContexts(['cookies:' . BigPipeStrategy::NOJS_COOKIE, 'session.exists']));
        return $response;
    
Production build 0.71.5 2024