{"componentChunkName":"component---src-templates-post-jsx","path":"/en/middleware-api","result":{"data":{"markdownRemark":{"html":"<h1>Middleware API: Efficient HTTP Request Management</h1>\n<p>In modern web application development, efficient management of HTTP requests is essential to ensure optimal performance, enhanced security, and a smooth user experience. Middleware APIs are powerful tools that allow HTTP requests to be processed flexibly and efficiently. In this article, we will explore Drupal's Middleware API in detail, highlighting its usage, how it works, and its advantages for Drupal developers.</p>\n<h2>What are Middleware APIs in Drupal?</h2>\n<p>Middleware APIs in Drupal are intermediate software layers that intercept and process HTTP requests before they reach route controllers or final services. They provide increased flexibility to modify, validate, or enrich HTTP requests based on the application's specific needs.</p>\n<h2>How Middleware APIs Work</h2>\n<p>Drupal's Middleware APIs follow a pipeline model, where each middleware intercepts the HTTP request, performs a specific action, and then passes the request to the next middleware in the chain. Middlewares can perform a variety of operations such as authentication, authorization, data validation, caching, and error handling.</p>\n<h2>Using Middleware APIs in Drupal</h2>\n<p>Here is an example of using Middleware APIs in Drupal:</p>\n<p>Suppose you need to authenticate incoming HTTP requests to your Drupal API by checking for an authentication token in the request header. You can use a middleware to intercept each incoming request, validate the token, and authorize access to protected resources.</p>\n<p>Here is how you could implement this in Drupal using a custom middleware:</p>\n<ul>\n<li>Create a new Drupal module (e.g., <code class=\"language-text\">custom_middleware</code>) and declare it in your <code class=\"language-text\">.info.yml</code> file.</li>\n<li>Create a class for your middleware in the <code class=\"language-text\">src/Middleware</code> folder of your module. For example, <code class=\"language-text\">CustomMiddleware.php</code>.</li>\n</ul>\n<div class=\"gatsby-highlight\" data-language=\"php\"><pre class=\"language-php\"><code class=\"language-php\"><span class=\"token comment\">// modules/custom/custom_middleware/src/Middleware/CustomMiddleware.php</span>\n\n<span class=\"token keyword\">namespace</span> <span class=\"token package\">Drupal<span class=\"token punctuation\">\\</span>custom_middleware<span class=\"token punctuation\">\\</span>Middleware</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">use</span> <span class=\"token package\">Symfony<span class=\"token punctuation\">\\</span>Component<span class=\"token punctuation\">\\</span>HttpFoundation<span class=\"token punctuation\">\\</span>Request</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">use</span> <span class=\"token package\">Symfony<span class=\"token punctuation\">\\</span>Component<span class=\"token punctuation\">\\</span>HttpFoundation<span class=\"token punctuation\">\\</span>Response</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">use</span> <span class=\"token package\">Symfony<span class=\"token punctuation\">\\</span>Component<span class=\"token punctuation\">\\</span>HttpKernel<span class=\"token punctuation\">\\</span>HttpKernelInterface</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">class</span> <span class=\"token class-name\">CustomMiddleware</span> <span class=\"token keyword\">implements</span> <span class=\"token class-name\">HttpKernelInterface</span> <span class=\"token punctuation\">{</span>\n\n  <span class=\"token keyword\">protected</span> <span class=\"token variable\">$httpKernel</span><span class=\"token punctuation\">;</span>\n\n  <span class=\"token keyword\">public</span> <span class=\"token keyword\">function</span> <span class=\"token function\">__construct</span><span class=\"token punctuation\">(</span>HttpKernelInterface <span class=\"token variable\">$http_kernel</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token variable\">$this</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token property\">httpKernel</span> <span class=\"token operator\">=</span> <span class=\"token variable\">$http_kernel</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">public</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handle</span><span class=\"token punctuation\">(</span>Request <span class=\"token variable\">$request</span><span class=\"token punctuation\">,</span> <span class=\"token variable\">$type</span> <span class=\"token operator\">=</span> self<span class=\"token punctuation\">:</span><span class=\"token punctuation\">:</span><span class=\"token constant\">MASTER_REQUEST</span><span class=\"token punctuation\">,</span> <span class=\"token variable\">$catch</span> <span class=\"token operator\">=</span> <span class=\"token boolean constant\">TRUE</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Check for an authentication token in the request header.</span>\n    <span class=\"token variable\">$token</span> <span class=\"token operator\">=</span> <span class=\"token variable\">$request</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token property\">headers</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token single-quoted-string string\">'Authorization'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token variable\">$this</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token function\">isValidToken</span><span class=\"token punctuation\">(</span><span class=\"token variable\">$token</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token comment\">// If the token is not valid, return a 401 Unauthorized error response.</span>\n      <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Response</span><span class=\"token punctuation\">(</span><span class=\"token single-quoted-string string\">'Unauthorized'</span><span class=\"token punctuation\">,</span> Response<span class=\"token punctuation\">:</span><span class=\"token punctuation\">:</span><span class=\"token constant\">HTTP_UNAUTHORIZED</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token comment\">// If the token is valid, pass the request to the next middleware in the chain.</span>\n    <span class=\"token keyword\">return</span> <span class=\"token variable\">$this</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token property\">httpKernel</span><span class=\"token operator\">-</span><span class=\"token operator\">></span><span class=\"token function\">handle</span><span class=\"token punctuation\">(</span><span class=\"token variable\">$request</span><span class=\"token punctuation\">,</span> <span class=\"token variable\">$type</span><span class=\"token punctuation\">,</span> <span class=\"token variable\">$catch</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">private</span> <span class=\"token keyword\">function</span> <span class=\"token function\">isValidToken</span><span class=\"token punctuation\">(</span><span class=\"token variable\">$token</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Implement your token validation logic here.</span>\n    <span class=\"token comment\">// For example, check if the token is valid in your authentication system.</span>\n    <span class=\"token comment\">// Returns TRUE if the token is valid, FALSE otherwise.</span>\n    <span class=\"token comment\">// This is a simplified example — adapt this method to your real needs.</span>\n    <span class=\"token keyword\">return</span> <span class=\"token variable\">$token</span> <span class=\"token operator\">===</span> <span class=\"token single-quoted-string string\">'my_secret_authentication_token'</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n\n<span class=\"token punctuation\">}</span></code></pre></div>\n<ul>\n<li>Register your middleware in Drupal's service container by creating a service file for your module.</li>\n</ul>\n<div class=\"gatsby-highlight\" data-language=\"yaml\"><pre class=\"language-yaml\"><code class=\"language-yaml\"><span class=\"token comment\"># modules/custom/custom_middleware/custom_middleware.services.yml</span>\n\n<span class=\"token key atrule\">services</span><span class=\"token punctuation\">:</span>\n  <span class=\"token key atrule\">custom_middleware.middleware</span><span class=\"token punctuation\">:</span>\n    <span class=\"token key atrule\">class</span><span class=\"token punctuation\">:</span> Drupal\\custom_middleware\\Middleware\\CustomMiddleware\n    <span class=\"token key atrule\">arguments</span><span class=\"token punctuation\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'@http_kernel'</span><span class=\"token punctuation\">]</span>\n    <span class=\"token key atrule\">tags</span><span class=\"token punctuation\">:</span>\n      <span class=\"token punctuation\">-</span> <span class=\"token punctuation\">{</span> <span class=\"token key atrule\">name</span><span class=\"token punctuation\">:</span> kernel.event_subscriber <span class=\"token punctuation\">}</span></code></pre></div>\n<p>With this middleware in place, every incoming request is intercepted and processed. If a valid authentication token is present in the request header, the request is passed to the next middleware in the chain. Otherwise, a 401 Unauthorized response is returned to the client.</p>\n<p>You can customize this middleware to suit your specific needs — for example, adding additional checks or implementing more complex authorization logic.</p>\n<h2>Advantages of Middleware APIs in Drupal</h2>\n<p>Middleware APIs offer several advantages for Drupal developers:</p>\n<ul>\n<li><strong>Flexibility</strong>: Middlewares provide increased flexibility to modify and enrich HTTP requests based on the application's specific needs.</li>\n<li><strong>Reusability</strong>: Middlewares can be reused across multiple API endpoints, reducing code redundancy and promoting consistency.</li>\n<li><strong>Separation of Concerns</strong>: Middlewares separate business logic from HTTP request management, which facilitates maintenance and scalability.</li>\n</ul>\n<h2>Conclusion</h2>\n<p>Middleware APIs are powerful tools for handling HTTP requests flexibly and efficiently in Drupal. By using Middleware APIs, Drupal developers can improve performance, enhance security, and deliver a better user experience in their web applications. With their flexibility, reusability, and ability to separate concerns, Middleware APIs are an essential component in any Drupal developer's toolkit.</p>","excerpt":"Middleware API: Efficient HTTP Request Management In modern web application development, efficient management of HTTP requests is essential to ensure optimal…","frontmatter":{"date":"2022-07-05","metaDate":"2022-07-05","title":"Middleware API","tags":["Drupal 9","Core feature","Performance","Module development"],"path":"/middleware-api","cover":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAIDBP/EABYBAQEBAAAAAAAAAAAAAAAAAAACBP/aAAwDAQACEAMQAAABx0k+mXJh/8QAGxABAAAHAAAAAAAAAAAAAAAAAQACEBIhMTL/2gAIAQEAAQUCIHF1JuTX/8QAFREBAQAAAAAAAAAAAAAAAAAAABH/2gAIAQMBAT8BR//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8BP//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEABj8CX//EABsQAAMAAgMAAAAAAAAAAAAAAAARIQEQMWGR/9oACAEBAAE/IckKykY/Xuog4D//2gAMAwEAAgADAAAAEG/v/8QAFhEAAwAAAAAAAAAAAAAAAAAAAAER/9oACAEDAQE/EGqSf//EABYRAQEBAAAAAAAAAAAAAAAAAAABEf/aAAgBAgEBPxCNf//EABkQAQEBAQEBAAAAAAAAAAAAAAERACExYf/aAAgBAQABPxAeEuVEU43U8k+q4O7geHEWkpv/2Q==","aspectRatio":1.5099533054804621,"src":"/static/e08cdf73f47a21fb5a1982ca17c58150/88110/picture.jpg","srcSet":"/static/e08cdf73f47a21fb5a1982ca17c58150/0b320/picture.jpg 480w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/60b32/picture.jpg 960w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/88110/picture.jpg 1920w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/40175/picture.jpg 2880w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/e58c2/picture.jpg 3840w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/4c335/picture.jpg 6144w","srcWebp":"/static/e08cdf73f47a21fb5a1982ca17c58150/d1a9d/picture.webp","srcSetWebp":"/static/e08cdf73f47a21fb5a1982ca17c58150/bc3bf/picture.webp 480w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/39337/picture.webp 960w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/d1a9d/picture.webp 1920w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/fcbe1/picture.webp 2880w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/c136d/picture.webp 3840w,\n/static/e08cdf73f47a21fb5a1982ca17c58150/e6706/picture.webp 6144w","sizes":"(max-width: 1920px) 100vw, 1920px"},"resize":{"src":"/static/e08cdf73f47a21fb5a1982ca17c58150/c4f3a/picture.jpg"}}}}}},"pageContext":{"isCreatedByStatefulCreatePages":false,"pathSlug":"/middleware-api","locale":"en","prev":{"fields":{"locale":"en"},"frontmatter":{"path":"/config-api-vs-state-api","title":"Configuration API vs State API","tags":["Drupal 8","Drupal 9","Backend","Configuration","State"]}},"next":{"fields":{"locale":"en"},"frontmatter":{"path":"/queue-api","title":"Queue API","tags":["Drupal 9","Drupal 10","backend","Module development"]}}}}}