How to add custom headers to every single response (globally) in Symfony 5

How to add custom headers to every single response (globally) in Symfony 5

Normally, if you need to add a global header to your website, it could be done through your webserver (apache or nginx). However, it's possible as well to add them globally or conditionally to your response in Symfony and not only within your controllers.

In this article, I will explain to you how to easily add custom headers to every single response in Symfony 5.

1. Create the RequestListener

To achieve this, you may simply register an event listener related to the kernel, specifically to the kernel.response event. This event is dispatched after the controller or any kernel.view listener returns a Response object. It’s useful to modify or replace the response before sending it back (e.g. add/modify HTTP headers, add cookies, etc.). Create the RequestListener.php file inside the src/EventListener directory with the following content:

<?php

// src/EventListener/RequestListener.php
namespace App\EventListener;

use Symfony\Component\HttpKernel\Event\ResponseEvent;

class RequestListener
{
    public function onKernelResponse(ResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            // don't do anything if it's not the master request
            return;
        }
        
        $response = $event->getResponse();
        
        // Set multiple headers simultaneously
        $response->headers->add([
            'Header-Name1' => 'value',
            'Header-Name2' => 'ExampleValue'
        ]);
        
        // Or set a single header
        $response->headers->set("Example-Header", "ExampleValue");
    }
}

2. Register EventListener

As final step, you only need to register the Request Listener in your services.yaml file like this:

# app/config/services.yaml

services:
    # Register EventListener onKernelResponse
    App\EventListener\RequestListener:
        tags:
            - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

Clear the cache of  your project and verify the headers of your website, you should see now the custom headers that you added:

Custom Headers Website Request

Happy coding ❤️!

This could interest you

Become a more social person