n Create custom middlewares in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application.

Code snippet that can be used to implement custom middleware to ban an IP address:

create mymodule.services.yml file: 

    class: Drupal\mymodule\CustomMiddleware
      - { name: http_middleware, priority: 150 }

create src/CustomMiddleware.php file:


namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

 * FirstMiddleware middleware.
class CustomMiddleware implements HttpKernelInterface {

    use StringTranslationTrait;

     * The kernel.
     * @var \Symfony\Component\HttpKernel\HttpKernelInterface
    protected $httpKernel;

     * Constructs the FirstMiddleware object.
     * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
     *   The decorated kernel.
    public function __construct(HttpKernelInterface $http_kernel) {
        $this->httpKernel = $http_kernel;

     * {@inheritdoc}
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
        if ($request->getClientIp() == '') {
            return new Response($this->t('hello world!'), 403);
        return $this->httpKernel->handle($request, $type, $catch);




Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook