When setting the form with ajax handler like this

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['actions']['submit'] = array(
      '#ajax' => [
        'wrapper' => 'custom_form_wrapper',
        'callback' => '::ajaxCallback',

function ajaxCallback() {
  $response = new AjaxResponse();
  $url = "www.example.com";
  $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand($url));

can I set $headers = ['custom' => 123] and pass this header to the redirected url? like we do in RedirectResponse().

So I can see this custom header in www.example.com

1 Answer 1


No, you cannot set headers in the same way as you do in RedirectResponse() when using RedirectCommand in an AJAX callback. The reason is that RedirectCommand uses JavaScript to redirect the user to the specified URL, and JavaScript does not have the ability to set headers.

If you need to pass headers to the redirected URL, you will need to do so on the server-side. One way to achieve this is to create a custom controller that handles the redirect, and then use RedirectResponse() with the headers you need. Here's an example:

Create a custom controller that handles the redirect and passes the necessary headers:

use Symfony\Component\HttpFoundation\RedirectResponse;

class MyController {
  public function redirectWithHeaders() {
    $url = 'http://www.example.com';
    $headers = [
      'custom' => 123,
    return new RedirectResponse($url, 302, $headers);

In your AJAX callback, use Url::fromRoute() to generate the URL for your custom controller, and then use RedirectCommand to redirect the user to that URL:

use Drupal\Core\Url;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;

function ajaxCallback() {
  $response = new AjaxResponse();
  $url = Url::fromRoute('my_module.redirect_with_headers');
  $response->addCommand(new RedirectCommand($url->toString()));
  return $response;

Note that you will need to define a route for your custom controller in a my_module.routing.yml file. Here's an example:

  path: '/redirect-with-headers'
    _controller: '\Drupal\my_module\Controller\MyController::redirectWithHeaders'
    _permission: 'access content'
  • Yes, using controller is the work around I have done. But there will be 2 redirects and this will affect in referrer path while getting analytics. But excluding analytics this can be the possible way. Thanks @Vikram8888
    – Viswa
    Commented Mar 2, 2023 at 13:17

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.